From bff75ed8718d84368f601e37984b839ed571787a Mon Sep 17 00:00:00 2001 From: Gehongyan Date: Tue, 14 Feb 2023 12:14:22 +0800 Subject: [PATCH] Applies code formatting --- .editorconfig | 113 + .../Configurations/KookBotConfigurations.cs | 6 +- .../Enums/BotEnvironment.cs | 4 +- .../Extensions/KookBotClientExtension.cs | 2 +- .../KookBotClientExtensionEventHandlers.cs | 38 +- .../Program.cs | 6 +- samples/Kook.Net.Samples.SimpleBot/Program.cs | 6 +- .../Modules/PublicModule.cs | 12 +- .../Kook.Net.Samples.TextCommands/Program.cs | 2 +- .../Services/CommandHandlingService.cs | 2 +- .../Services/PictureService.cs | 2 +- .../Attributes/AliasAttribute.cs | 2 +- .../Attributes/CommandAttribute.cs | 2 +- .../Attributes/DontAutoLoadAttribute.cs | 2 +- .../Attributes/DontInjectAttribute.cs | 2 +- .../Attributes/GroupAttribute.cs | 2 +- .../Attributes/NameAttribute.cs | 2 +- .../Attributes/NamedArgumentTypeAttribute.cs | 2 +- .../Attributes/OverrideTypeReaderAttribute.cs | 4 +- .../ParameterPreconditionAttribute.cs | 2 +- .../Attributes/PreconditionAttribute.cs | 2 +- .../RequireBotPermissionAttribute.cs | 2 +- .../Preconditions/RequireContextAttribute.cs | 2 +- .../Preconditions/RequireUserAttribute.cs | 6 +- .../RequireUserPermissionAttribute.cs | 4 +- .../Attributes/PriorityAttribute.cs | 2 +- .../Attributes/RemainderAttribute.cs | 2 +- .../Attributes/RemarksAttribute.cs | 2 +- .../Attributes/SummaryAttribute.cs | 2 +- .../Builders/CommandBuilder.cs | 4 +- .../Builders/ModuleBuilder.cs | 6 +- .../Builders/ModuleClassBuilder.cs | 19 +- .../Builders/ParameterBuilder.cs | 5 +- src/Kook.Net.Commands/CommandContext.cs | 2 +- src/Kook.Net.Commands/CommandError.cs | 2 +- src/Kook.Net.Commands/CommandException.cs | 2 +- src/Kook.Net.Commands/CommandMatch.cs | 2 +- src/Kook.Net.Commands/CommandParser.cs | 2 +- src/Kook.Net.Commands/CommandService.cs | 10 +- src/Kook.Net.Commands/CommandServiceConfig.cs | 4 +- src/Kook.Net.Commands/EmptyServiceProvider.cs | 4 +- .../Extensions/CommandServiceExtensions.cs | 2 +- .../Extensions/IEnumerableExtensions.cs | 2 +- .../Extensions/MessageExtensions.cs | 28 +- src/Kook.Net.Commands/IModuleBase.cs | 4 +- src/Kook.Net.Commands/Info/CommandInfo.cs | 6 +- src/Kook.Net.Commands/Info/ModuleInfo.cs | 6 +- src/Kook.Net.Commands/Info/ParameterInfo.cs | 2 +- src/Kook.Net.Commands/Map/CommandMap.cs | 2 +- src/Kook.Net.Commands/Map/CommandMapNode.cs | 2 +- src/Kook.Net.Commands/ModuleBase.cs | 10 +- src/Kook.Net.Commands/MultiMatchHandling.cs | 2 +- src/Kook.Net.Commands/PrimitiveParsers.cs | 2 +- .../Readers/ChannelTypeReader.cs | 4 +- .../Readers/EnumTypeReader.cs | 6 +- .../Readers/MessageTypeReader.cs | 2 +- .../Readers/NamedArgumentTypeReader.cs | 4 +- .../Readers/NullableTypeReader.cs | 2 +- .../Readers/PrimitiveTypeReader.cs | 2 +- .../Readers/RoleTypeReader.cs | 4 +- .../Readers/TimeSpanTypeReader.cs | 2 +- src/Kook.Net.Commands/Readers/TypeReader.cs | 2 +- .../Readers/UserTypeReader.cs | 6 +- .../Results/ExecuteResult.cs | 2 +- src/Kook.Net.Commands/Results/IResult.cs | 2 +- src/Kook.Net.Commands/Results/MatchResult.cs | 6 +- src/Kook.Net.Commands/Results/ParseResult.cs | 2 +- .../Results/PreconditionGroupResult.cs | 2 +- .../Results/PreconditionResult.cs | 2 +- .../Results/RuntimeResult.cs | 2 +- src/Kook.Net.Commands/Results/SearchResult.cs | 2 +- .../Results/TypeReaderResult.cs | 2 +- src/Kook.Net.Commands/RunMode.cs | 2 +- .../Utilities/QuotationAliasUtils.cs | 2 +- .../Utilities/ReflectionUtils.cs | 4 +- src/Kook.Net.Core/AssemblyInfo.cs | 2 +- src/Kook.Net.Core/Audio/AudioApplication.cs | 2 +- src/Kook.Net.Core/Audio/AudioInStream.cs | 6 +- src/Kook.Net.Core/Audio/AudioOutStream.cs | 2 +- src/Kook.Net.Core/Audio/AudioStream.cs | 6 +- src/Kook.Net.Core/Audio/IAudioClient.cs | 2 +- src/Kook.Net.Core/Audio/RTPFrame.cs | 2 +- src/Kook.Net.Core/Commands/ICommandContext.cs | 2 +- src/Kook.Net.Core/ConnectionState.cs | 2 +- .../Entities/Activities/ActivityType.cs | 2 +- .../Entities/Activities/GameProperties.cs | 2 +- .../Entities/Activities/GameType.cs | 2 +- .../Entities/Activities/IActivity.cs | 4 +- .../Entities/Activities/IGame.cs | 2 +- .../Entities/Activities/Music.cs | 2 +- .../Entities/Activities/MusicProvider.cs | 2 +- .../Entities/Badges/BadgeStyle.cs | 2 +- src/Kook.Net.Core/Entities/CacheMode.cs | 2 +- .../Entities/Channels/ChannelType.cs | 12 +- .../CreateCategoryChannelProperties.cs | 2 +- .../Channels/CreateGuildChannelProperties.cs | 2 +- .../Channels/CreateTextChannelProperties.cs | 4 +- .../Channels/CreateVoiceChannelProperties.cs | 6 +- .../Entities/Channels/Direction.cs | 2 +- .../Entities/Channels/IAudioChannel.cs | 6 +- .../Entities/Channels/ICategoryChannel.cs | 6 +- .../Entities/Channels/IChannel.cs | 8 +- .../Entities/Channels/IDMChannel.cs | 8 +- .../Entities/Channels/IGuildChannel.cs | 18 +- .../Entities/Channels/IMessageChannel.cs | 28 +- .../Entities/Channels/INestedChannel.cs | 12 +- .../Entities/Channels/IPrivateChannel.cs | 2 +- .../Entities/Channels/ITextChannel.cs | 10 +- .../Entities/Channels/IVoiceChannel.cs | 10 +- .../Entities/Channels/MessageSource.cs | 4 +- .../Channels/ModifyGuildChannelProperties.cs | 2 +- .../Channels/ModifyTextChannelProperties.cs | 2 +- .../Channels/ModifyVoiceChannelProperties.cs | 2 +- .../Entities/Channels/SlowModeInterval.cs | 2 +- .../Entities/Channels/VoiceQuality.cs | 2 +- src/Kook.Net.Core/Entities/Emotes/Emoji.cs | 8 +- .../Entities/Emotes/EmojiType.cs | 2 +- src/Kook.Net.Core/Entities/Emotes/Emote.cs | 36 +- .../Entities/Emotes/GuildEmote.cs | 10 +- src/Kook.Net.Core/Entities/Emotes/IEmote.cs | 4 +- .../Entities/Guilds/BoostLevel.cs | 2 +- src/Kook.Net.Core/Entities/Guilds/IBan.cs | 2 +- src/Kook.Net.Core/Entities/Guilds/IGuild.cs | 26 +- .../Entities/Guilds/IRecommendInfo.cs | 2 +- .../Entities/Guilds/NotifyType.cs | 10 +- src/Kook.Net.Core/Entities/Guilds/RoleType.cs | 2 +- src/Kook.Net.Core/Entities/IDeletable.cs | 2 +- src/Kook.Net.Core/Entities/IEntity.cs | 6 +- src/Kook.Net.Core/Entities/IMentionable.cs | 4 +- src/Kook.Net.Core/Entities/IUpdateable.cs | 2 +- src/Kook.Net.Core/Entities/Image.cs | 5 +- .../Entities/Intimacies/IIntimacy.cs | 6 +- .../Entities/Intimacies/IntimacyImage.cs | 2 +- .../Entities/Intimacies/IntimacyProperties.cs | 2 +- src/Kook.Net.Core/Entities/Invites/IInvite.cs | 6 +- .../Entities/Invites/InviteMaxAge.cs | 2 +- .../Entities/Invites/InviteMaxUses.cs | 2 +- .../Entities/Messages/AttachmentType.cs | 4 +- .../Entities/Messages/Cards/Card.cs | 12 +- .../Entities/Messages/Cards/CardBuilder.cs | 18 +- .../Entities/Messages/Cards/CardSize.cs | 4 +- .../Entities/Messages/Cards/CardTheme.cs | 4 +- .../Entities/Messages/Cards/CardType.cs | 4 +- .../Cards/Elements/ButtonClickEventType.cs | 4 +- .../Messages/Cards/Elements/ButtonElement.cs | 6 +- .../Messages/Cards/Elements/ButtonTheme.cs | 4 +- .../Messages/Cards/Elements/ElementBuilder.cs | 74 +- .../Messages/Cards/Elements/ElementType.cs | 4 +- .../Messages/Cards/Elements/IElement.cs | 4 +- .../Cards/Elements/IElementBuilder.cs | 4 +- .../Messages/Cards/Elements/ImageElement.cs | 4 +- .../Messages/Cards/Elements/ImageSize.cs | 4 +- .../Cards/Elements/KMarkdownElement.cs | 2 +- .../Cards/Elements/ParagraphStruct.cs | 6 +- .../Cards/Elements/PlainTextElement.cs | 2 +- .../Messages/Cards/Elements/TextTheme.cs | 2 +- .../Entities/Messages/Cards/ICard.cs | 6 +- .../Entities/Messages/Cards/ICardBuilder.cs | 4 +- .../Cards/Modules/ActionGroupModule.cs | 12 +- .../Messages/Cards/Modules/AudioModule.cs | 14 +- .../Messages/Cards/Modules/ContainerModule.cs | 12 +- .../Messages/Cards/Modules/ContextModule.cs | 10 +- .../Messages/Cards/Modules/CountdownMode.cs | 4 +- .../Messages/Cards/Modules/CountdownModule.cs | 12 +- .../Messages/Cards/Modules/DividerModule.cs | 12 +- .../Messages/Cards/Modules/FileModule.cs | 10 +- .../Messages/Cards/Modules/HeaderModule.cs | 8 +- .../Messages/Cards/Modules/IMediaModule.cs | 4 +- .../Messages/Cards/Modules/IModule.cs | 4 +- .../Messages/Cards/Modules/IModuleBuilder.cs | 4 +- .../Cards/Modules/ImageGroupModule.cs | 12 +- .../Messages/Cards/Modules/InviteModule.cs | 8 +- .../Messages/Cards/Modules/ModuleBuilder.cs | 32 +- .../Messages/Cards/Modules/ModuleType.cs | 4 +- .../Cards/Modules/SectionAccessoryMode.cs | 4 +- .../Messages/Cards/Modules/SectionModule.cs | 8 +- .../Messages/Cards/Modules/VideoModule.cs | 10 +- .../Entities/Messages/CreateAttachmentMode.cs | 6 +- .../Messages/Embeds/BilibiliVideoEmbed.cs | 6 +- .../Entities/Messages/Embeds/EmbedType.cs | 2 +- .../Entities/Messages/Embeds/IEmbed.cs | 4 +- .../Entities/Messages/Embeds/ImageEmbed.cs | 6 +- .../Entities/Messages/Embeds/LinkEmbed.cs | 6 +- .../Messages/Embeds/NotImplementedEmbed.cs | 8 +- .../Entities/Messages/FileAttachment.cs | 4 +- .../Entities/Messages/IAttachment.cs | 12 +- .../Entities/Messages/IMessage.cs | 48 +- src/Kook.Net.Core/Entities/Messages/IQuote.cs | 10 +- .../Entities/Messages/IReaction.cs | 2 +- .../Entities/Messages/ISystemMessage.cs | 4 +- src/Kook.Net.Core/Entities/Messages/ITag.cs | 12 +- .../Entities/Messages/IUserMessage.cs | 8 +- .../Entities/Messages/MessageProperties.cs | 2 +- .../Entities/Messages/MessageType.cs | 4 +- .../Entities/Messages/Pokes/IPoke.cs | 2 +- .../Entities/Messages/Pokes/IPokeAction.cs | 2 +- .../Entities/Messages/Pokes/PokeIcon.cs | 2 +- .../Entities/Messages/Pokes/PokeLabel.cs | 4 +- .../Entities/Messages/Pokes/PokeQuality.cs | 10 +- .../Pokes/PokeResources/IPokeResource.cs | 2 +- .../ImageAnimationPokeResource.cs | 10 +- .../NotImplementedPokeResource.cs | 12 +- .../Pokes/PokeResources/PokeResourceType.cs | 2 +- src/Kook.Net.Core/Entities/Messages/Quote.cs | 6 +- .../Entities/Messages/ReactionMetadata.cs | 2 +- .../Entities/Messages/SystemMessageType.cs | 6 +- src/Kook.Net.Core/Entities/Messages/Tag.cs | 6 +- .../Entities/Messages/TagHandling.cs | 2 +- .../Entities/Messages/TagMode.cs | 2 +- .../Entities/Messages/TagType.cs | 2 +- .../Entities/Permissions/ChannelPermission.cs | 40 +- .../Permissions/ChannelPermissions.cs | 14 +- .../Entities/Permissions/GuildPermission.cs | 62 +- .../Entities/Permissions/GuildPermissions.cs | 16 +- .../Permissions/IPermissionOverwrite.cs | 6 +- .../Permissions/OverwritePermissions.cs | 16 +- .../Entities/Permissions/PermValue.cs | 4 +- .../Permissions/RolePermissionOverwrite.cs | 8 +- .../Permissions/UserPermissionOverwrite.cs | 8 +- src/Kook.Net.Core/Entities/Roles/Color.cs | 2 +- src/Kook.Net.Core/Entities/Roles/IRole.cs | 4 +- .../Entities/Roles/RoleProperties.cs | 2 +- src/Kook.Net.Core/Entities/SortMode.cs | 2 +- .../Entities/Users/ClientType.cs | 2 +- .../Entities/Users/IGuildUser.cs | 20 +- src/Kook.Net.Core/Entities/Users/IPresence.cs | 2 +- src/Kook.Net.Core/Entities/Users/ISelfUser.cs | 2 +- src/Kook.Net.Core/Entities/Users/IUser.cs | 8 +- .../Entities/Users/IVoiceState.cs | 2 +- .../Users/SearchGuildMemberProperties.cs | 2 +- src/Kook.Net.Core/Entities/Users/UserTag.cs | 23 +- .../Extensions/AsyncEnumerableExtensions.cs | 2 +- .../Extensions/ChannelExtensions.cs | 4 +- .../Extensions/CollectionExtensions.cs | 2 +- .../Extensions/MessageExtensions.cs | 18 +- .../TaskCompletionSourceExtensions.cs | 4 +- .../Extensions/UserExtensions.cs | 6 +- src/Kook.Net.Core/Format.cs | 5 +- src/Kook.Net.Core/IKookClient.cs | 18 +- src/Kook.Net.Core/KookConfig.cs | 22 +- src/Kook.Net.Core/KookErrorCode.cs | 6 +- src/Kook.Net.Core/KookJsonError.cs | 2 +- src/Kook.Net.Core/Logging/LogManager.cs | 2 +- src/Kook.Net.Core/Logging/LogMessage.cs | 6 +- src/Kook.Net.Core/Logging/LogSeverity.cs | 2 +- src/Kook.Net.Core/Logging/Logger.cs | 2 +- src/Kook.Net.Core/LoginState.cs | 2 +- src/Kook.Net.Core/Net/BucketId.cs | 6 +- src/Kook.Net.Core/Net/HttpException.cs | 4 +- src/Kook.Net.Core/Net/IRequest.cs | 2 +- src/Kook.Net.Core/Net/RateLimitedException.cs | 2 +- src/Kook.Net.Core/Net/Rest/IRateLimitInfo.cs | 2 +- src/Kook.Net.Core/Net/Rest/IRestClient.cs | 2 +- .../Net/Rest/RestClientProvider.cs | 4 +- src/Kook.Net.Core/Net/Rest/RestResponse.cs | 6 +- src/Kook.Net.Core/Net/Udp/IUdpSocket.cs | 4 +- .../Net/Udp/UdpSocketProvider.cs | 4 +- .../Net/WebSocketClosedException.cs | 2 +- .../Net/WebSockets/IWebSocketClient.cs | 4 +- .../Net/WebSockets/WebSocketProvider.cs | 4 +- src/Kook.Net.Core/RequestOptions.cs | 10 +- src/Kook.Net.Core/RetryMode.cs | 2 +- src/Kook.Net.Core/TokenType.cs | 2 +- src/Kook.Net.Core/Utils/AsyncEvent.cs | 4 +- src/Kook.Net.Core/Utils/Cacheable.cs | 4 +- src/Kook.Net.Core/Utils/ConcurrentHashSet.cs | 70 +- src/Kook.Net.Core/Utils/MentionUtils.cs | 22 +- src/Kook.Net.Core/Utils/Paging/Page.cs | 4 +- src/Kook.Net.Core/Utils/Paging/PageInfo.cs | 4 +- .../Utils/Paging/PagedEnumerator.cs | 4 +- src/Kook.Net.Core/Utils/Permissions.cs | 24 +- src/Kook.Net.Core/Utils/Preconditions.cs | 32 +- src/Kook.Net.Core/Utils/TokenUtils.cs | 2 +- src/Kook.Net.Core/Utils/UrlValidation.cs | 8 +- .../Core/Entities/Guilds/GuildProperties.cs | 2 +- .../Core/Entities/Guilds/IVoiceRegion.cs | 2 +- .../Rest/API/Common/VoiceRegion.cs | 4 +- .../Rest/API/Rest/CreateGuildParams.cs | 2 +- .../Rest/API/Rest/DeleteGuildParams.cs | 4 +- .../Rest/API/Rest/DisconnectUserParams.cs | 4 +- .../Rest/API/Rest/ModifyGuildParams.cs | 2 +- .../API/Rest/SyncChannelPermissionsParams.cs | 4 +- .../Channels/ExperimentalChannelHelper.cs | 2 +- .../RestTextChannelExperimentalExtensions.cs | 2 +- .../RestVoiceChannelExperimentalExtensions.cs | 2 +- .../Guilds/ExperimentalGuildHelper.cs | 7 +- .../Rest/Entities/Guilds/RestVoiceRegion.cs | 4 +- .../Rest/ExperimentalClientHelper.cs | 4 +- ...KookRestApiClientExperimentalExtensions.cs | 4 +- .../Converters/ImageBase64DataUriConverter.cs | 2 +- ...SocketTextChannelExperimentalExtensions.cs | 2 +- ...ocketVoiceChannelExperimentalExtensions.cs | 2 +- src/Kook.Net.Rest/API/Common/Attachment.cs | 2 +- src/Kook.Net.Rest/API/Common/Ban.cs | 4 +- src/Kook.Net.Rest/API/Common/Cards/Card.cs | 4 +- .../API/Common/Cards/CardBase.cs | 4 +- .../Common/Cards/Elements/ButtonElement.cs | 4 +- .../API/Common/Cards/Elements/ElementBase.cs | 4 +- .../API/Common/Cards/Elements/IElement.cs | 2 +- .../API/Common/Cards/Elements/ImageElement.cs | 4 +- .../Common/Cards/Elements/KMarkdownElement.cs | 2 +- .../Common/Cards/Elements/ParagraphStruct.cs | 4 +- .../Common/Cards/Elements/PlainTextElement.cs | 2 +- src/Kook.Net.Rest/API/Common/Cards/ICard.cs | 2 +- .../Common/Cards/Modules/ActionGroupModule.cs | 4 +- .../API/Common/Cards/Modules/AudioModule.cs | 2 +- .../Common/Cards/Modules/ContainerModule.cs | 4 +- .../API/Common/Cards/Modules/ContextModule.cs | 4 +- .../Common/Cards/Modules/CountdownModule.cs | 8 +- .../API/Common/Cards/Modules/DividerModule.cs | 4 +- .../API/Common/Cards/Modules/FileModule.cs | 2 +- .../API/Common/Cards/Modules/HeaderModule.cs | 2 +- .../API/Common/Cards/Modules/IModule.cs | 4 +- .../Common/Cards/Modules/ImageGroupModule.cs | 4 +- .../API/Common/Cards/Modules/InviteModule.cs | 2 +- .../API/Common/Cards/Modules/ModuleBase.cs | 4 +- .../API/Common/Cards/Modules/SectionModule.cs | 4 +- .../API/Common/Cards/Modules/VideoModule.cs | 2 +- src/Kook.Net.Rest/API/Common/Channel.cs | 16 +- src/Kook.Net.Rest/API/Common/DirectMessage.cs | 14 +- .../API/Common/Embeds/BilibiliVideoEmbed.cs | 12 +- .../API/Common/Embeds/EmbedBase.cs | 4 +- src/Kook.Net.Rest/API/Common/Embeds/IEmbed.cs | 2 +- .../API/Common/Embeds/ImageEmbed.cs | 2 +- .../API/Common/Embeds/LinkEmbed.cs | 4 +- .../API/Common/Embeds/NotImplementedEmbed.cs | 4 +- src/Kook.Net.Rest/API/Common/Emoji.cs | 6 +- src/Kook.Net.Rest/API/Common/Game.cs | 16 +- src/Kook.Net.Rest/API/Common/Guild.cs | 4 +- src/Kook.Net.Rest/API/Common/Intimacy.cs | 6 +- src/Kook.Net.Rest/API/Common/Invite.cs | 10 +- src/Kook.Net.Rest/API/Common/MentionInfo.cs | 2 +- src/Kook.Net.Rest/API/Common/MentionRole.cs | 4 +- .../API/Common/MentionedChannel.cs | 4 +- src/Kook.Net.Rest/API/Common/MentionedUser.cs | 2 +- src/Kook.Net.Rest/API/Common/Message.cs | 14 +- .../API/Common/Pokes/IPokeResource.cs | 2 +- .../Pokes/ImageAnimationPokeResource.cs | 2 +- .../Pokes/NotImplementedPokeResource.cs | 4 +- .../API/Common/Pokes/PokeQualityResource.cs | 4 +- .../API/Common/Pokes/PokeResourceBase.cs | 4 +- src/Kook.Net.Rest/API/Common/Quote.cs | 4 +- src/Kook.Net.Rest/API/Common/Reaction.cs | 2 +- src/Kook.Net.Rest/API/Common/RecommendInfo.cs | 46 +- src/Kook.Net.Rest/API/Common/Role.cs | 2 +- .../API/Common/RolePermissionOverwrite.cs | 2 +- src/Kook.Net.Rest/API/Common/Tag.cs | 2 +- src/Kook.Net.Rest/API/Common/User.cs | 4 +- src/Kook.Net.Rest/API/Common/UserChat.cs | 4 +- .../API/Common/UserPermissionOverwrite.cs | 2 +- src/Kook.Net.Rest/API/Common/UserTag.cs | 4 +- src/Kook.Net.Rest/API/Net/MultipartFile.cs | 2 +- .../API/Rest/AddOrRemoveRoleParams.cs | 4 +- .../API/Rest/AddOrRemoveRoleResponsecs.cs | 2 +- .../API/Rest/AddReactionParams.cs | 4 +- .../API/Rest/BeginActivityParams.cs | 10 +- .../API/Rest/BoostSubscription.cs | 2 +- .../API/Rest/CreateAssetParams.cs | 4 +- .../API/Rest/CreateAssetResponse.cs | 2 +- .../API/Rest/CreateDirectMessageParams.cs | 6 +- .../API/Rest/CreateDirectMessageResponse.cs | 4 +- .../API/Rest/CreateGameParams.cs | 6 +- .../API/Rest/CreateGuildBanParams.cs | 8 +- .../API/Rest/CreateGuildChannelParams.cs | 8 +- .../API/Rest/CreateGuildEmoteParams.cs | 6 +- .../API/Rest/CreateGuildInviteParams.cs | 4 +- .../API/Rest/CreateGuildInviteResponse.cs | 2 +- .../API/Rest/CreateGuildRoleParams.cs | 2 +- .../API/Rest/CreateMessageParams.cs | 6 +- .../API/Rest/CreateMessageResponse.cs | 4 +- ...odifyChannelPermissionOverwriteResponse.cs | 20 +- ...rRemoveChannelPermissionOverwriteParams.cs | 6 +- .../Rest/CreateOrRemoveGuildMuteDeafParams.cs | 6 +- .../API/Rest/CreateUserChatParams.cs | 4 +- .../API/Rest/DeleteDirectMessageParams.cs | 6 +- .../API/Rest/DeleteGameParams.cs | 6 +- .../API/Rest/DeleteGuildChannelParams.cs | 4 +- .../API/Rest/DeleteGuildEmoteParams.cs | 4 +- .../API/Rest/DeleteGuildInviteParams.cs | 6 +- .../API/Rest/DeleteGuildRoleParams.cs | 2 +- .../API/Rest/DeleteMessageParams.cs | 6 +- .../API/Rest/DeleteUserChatParams.cs | 6 +- .../API/Rest/EndGameActivityParams.cs | 4 +- src/Kook.Net.Rest/API/Rest/ExtendedGuild.cs | 4 +- .../API/Rest/GetBotGatewayResponse.cs | 2 +- .../GetChannelPermissionOverwritesResponse.cs | 10 +- .../API/Rest/GetGuildMemberCountResponse.cs | 2 +- .../API/Rest/GetGuildMuteDeafListResponse.cs | 8 +- .../API/Rest/GetVoiceGatewayResponse.cs | 2 +- src/Kook.Net.Rest/API/Rest/GuildMember.cs | 6 +- .../API/Rest/KickOutGuildMemberParams.cs | 4 +- .../API/Rest/LeaveGuildParams.cs | 4 +- .../ModifyChannelPermissionOverwriteParams.cs | 10 +- .../API/Rest/ModifyDirectMessageParams.cs | 4 +- .../API/Rest/ModifyGameParams.cs | 6 +- .../API/Rest/ModifyGuildChannelParams.cs | 14 +- .../API/Rest/ModifyGuildEmoteParams.cs | 4 +- .../Rest/ModifyGuildMemberNicknameParams.cs | 4 +- .../API/Rest/ModifyGuildRoleParams.cs | 4 +- .../API/Rest/ModifyMessageParams.cs | 4 +- .../API/Rest/ModifyTextChannelParams.cs | 6 +- .../API/Rest/ModifyVoiceChannelParams.cs | 4 +- src/Kook.Net.Rest/API/Rest/MoveUsersParams.cs | 4 +- src/Kook.Net.Rest/API/Rest/MuteOrDeafType.cs | 2 +- .../API/Rest/PagedResponseBase.cs | 10 +- .../API/Rest/PermissionOverwriteTargetType.cs | 2 +- .../API/Rest/QueryMessagesResponse.cs | 2 +- .../API/Rest/QueryUserChatMessagesResponse.cs | 2 +- .../API/Rest/ReactionUserResponse.cs | 4 +- .../API/Rest/RemoveGuildBanParams.cs | 2 +- .../API/Rest/RemoveReactionParams.cs | 4 +- .../API/Rest/RestResponseBase.cs | 6 +- src/Kook.Net.Rest/API/Rest/RichGuild.cs | 6 +- src/Kook.Net.Rest/API/Rest/SelfUser.cs | 2 +- src/Kook.Net.Rest/API/Rest/SortMode.cs | 2 +- .../API/Rest/UpdateIntimacyValueParams.cs | 2 +- src/Kook.Net.Rest/AssemblyInfo.cs | 2 +- src/Kook.Net.Rest/BaseKookClient.cs | 37 +- src/Kook.Net.Rest/ClientHelper.cs | 20 +- .../Entities/Channels/ChannelHelper.cs | 40 +- .../Entities/Channels/IRestAudioChannel.cs | 4 +- .../Entities/Channels/IRestMessageChannel.cs | 2 +- .../Entities/Channels/IRestPrivateChannel.cs | 2 +- .../Entities/Channels/RestCategoryChannel.cs | 17 +- .../Entities/Channels/RestChannel.cs | 8 +- .../Entities/Channels/RestDMChannel.cs | 40 +- .../Entities/Channels/RestGuildChannel.cs | 39 +- .../Entities/Channels/RestTextChannel.cs | 59 +- .../Entities/Channels/RestVoiceChannel.cs | 31 +- .../Entities/Games/GameHelper.cs | 4 +- src/Kook.Net.Rest/Entities/Games/RestGame.cs | 12 +- .../Entities/Guilds/GuildHelper.cs | 77 +- .../Entities/Guilds/RecommendInfo.cs | 4 +- src/Kook.Net.Rest/Entities/Guilds/RestBan.cs | 12 +- .../Entities/Guilds/RestGuild.cs | 70 +- .../Entities/Intimacies/IntimacyHelper.cs | 2 +- .../Entities/Intimacies/RestIntimacy.cs | 6 +- .../Entities/Invites/InviteHelper.cs | 4 +- .../Entities/Invites/RestInvite.cs | 12 +- .../Entities/Messages/Attachment.cs | 6 +- .../Entities/Messages/MessageHelper.cs | 89 +- src/Kook.Net.Rest/Entities/Messages/Poke.cs | 6 +- .../Entities/Messages/RestMessage.cs | 30 +- .../Entities/Messages/RestPokeAction.cs | 4 +- .../Entities/Messages/RestReaction.cs | 4 +- .../Entities/Messages/RestSystemMessage.cs | 6 +- .../Entities/Messages/RestUserMessage.cs | 34 +- src/Kook.Net.Rest/Entities/RestEntity.cs | 4 +- src/Kook.Net.Rest/Entities/Roles/RestRole.cs | 22 +- .../Entities/Roles/RoleHelper.cs | 2 +- .../Entities/Users/RestGuildUser.cs | 38 +- .../Entities/Users/RestPresence.cs | 6 +- .../Entities/Users/RestSelfUser.cs | 10 +- src/Kook.Net.Rest/Entities/Users/RestUser.cs | 24 +- .../Entities/Users/UserHelper.cs | 2 +- .../Extensions/EntityExtensions.cs | 159 +- src/Kook.Net.Rest/KookRestApiClient.cs | 292 ++- src/Kook.Net.Rest/KookRestClient.cs | 28 +- src/Kook.Net.Rest/KookRestConfig.cs | 2 +- .../Cards/ButtonClickEventTypeConverter.cs | 2 +- .../Converters/Cards/ButtonThemeConverter.cs | 2 +- .../Net/Converters/Cards/CardConverter.cs | 6 +- .../Net/Converters/Cards/CardSizeConverter.cs | 2 +- .../Converters/Cards/CardThemeConverter.cs | 2 +- .../Net/Converters/Cards/CardTypeConverter.cs | 2 +- .../Net/Converters/Cards/ColorConverter.cs | 2 +- .../Cards/CountdownModeConverter.cs | 2 +- .../Net/Converters/Cards/ElementConverter.cs | 4 +- .../Converters/Cards/ElementTypeConverter.cs | 2 +- .../Converters/Cards/ImageSizeConverter.cs | 2 +- .../Net/Converters/Cards/ModuleConverter.cs | 6 +- .../Converters/Cards/ModuleTypeConverter.cs | 2 +- .../Cards/NullableColorConverter.cs | 2 +- .../Cards/SectionAccessoryModeConvertercs.cs | 2 +- .../Net/Converters/ChatCodeConverter.cs | 2 +- ...TimeOffsetUnixTimeMillisecondsConverter.cs | 2 +- .../DateTimeOffsetUnixTimeSecondsConverter.cs | 2 +- .../Net/Converters/Embeds/EmbedConverter.cs | 4 +- .../Converters/Embeds/EmbedTypeConverter.cs | 2 +- .../Net/Converters/MusicProviderConverter.cs | 2 +- .../Converters/NullableChatCodeConverter.cs | 11 +- .../NullableDateTimeOffsetConverter.cs | 11 +- .../Net/Converters/NullableGuidConverter.cs | 11 +- .../NullableNumberBooleanConverter.cs | 2 +- .../Converters/NullableTimeSpanConverter.cs | 11 +- .../Net/Converters/NullableUInt32Converter.cs | 10 +- .../Net/Converters/NullableUInt64Converter.cs | 12 +- .../NullableVoiceQualityConverter.cs | 12 +- .../Net/Converters/NumberBooleanConverter.cs | 2 +- .../Net/Converters/PageSortInfoConverter.cs | 6 +- .../PermissionOverwriteTargetTypeConverter.cs | 4 +- .../Converters/Pokes/PokeResourceConverter.cs | 4 +- .../Pokes/PokeResourceTypeConverter.cs | 2 +- src/Kook.Net.Rest/Net/DefaultRestClient.cs | 52 +- .../Net/DefaultRestClientProvider.cs | 2 +- src/Kook.Net.Rest/Net/Queue/ClientBucket.cs | 4 +- src/Kook.Net.Rest/Net/Queue/GatewayBucket.cs | 2 +- src/Kook.Net.Rest/Net/Queue/RequestQueue.cs | 4 +- .../Net/Queue/RequestQueueBucket.cs | 55 +- .../Net/Queue/Requests/JsonRestRequest.cs | 4 +- .../Queue/Requests/MultipartRestRequest.cs | 4 +- .../Net/Queue/Requests/RestRequest.cs | 2 +- .../Net/Queue/Requests/WebSocketRequest.cs | 2 +- src/Kook.Net.Rest/Net/RateLimitInfo.cs | 6 +- .../API/Gateway/ChannelDeleteEvent.cs | 6 +- .../API/Gateway/DirectMessageDeleteEvent.cs | 14 +- .../API/Gateway/DirectMessageUpdateEvent.cs | 18 +- .../API/Gateway/GatewayEvent.cs | 4 +- .../Gateway/GatewayGroupMessageExtraData.cs | 10 +- .../API/Gateway/GatewayHelloPayload.cs | 6 +- .../Gateway/GatewayPersonMessageExtraData.cs | 14 +- .../API/Gateway/GatewayReconnectPayload.cs | 6 +- .../API/Gateway/GatewaySocketFrame.cs | 4 +- .../API/Gateway/GatewaySocketFrameType.cs | 2 +- .../Gateway/GatewaySystemEventExtraData.cs | 4 +- .../API/Gateway/GuildBanEvent.cs | 6 +- .../API/Gateway/GuildEmojiEvent.cs | 2 +- .../API/Gateway/GuildEvent.cs | 34 +- .../API/Gateway/GuildMemberAddEvent.cs | 6 +- .../API/Gateway/GuildMemberOfflineEvent.cs | 6 +- .../API/Gateway/GuildMemberOnlineEvent.cs | 6 +- .../API/Gateway/GuildMemberRemoveEvent.cs | 6 +- .../API/Gateway/GuildMemberUpdateEvent.cs | 6 +- .../API/Gateway/KMarkdownInfo.cs | 4 +- .../API/Gateway/MessageButtonClickEvent.cs | 10 +- .../API/Gateway/MessageDeleteEvent.cs | 6 +- .../API/Gateway/MessageUpdateEvent.cs | 16 +- .../API/Gateway/PinnedMessageEvent.cs | 10 +- .../API/Gateway/PrivateReaction.cs | 4 +- .../API/Gateway/Reaction.cs | 2 +- .../API/Gateway/SelfGuildEvent.cs | 2 +- .../API/Gateway/UnpinnedMessageEvent.cs | 10 +- .../API/Gateway/UserUpdateEvent.cs | 6 +- .../API/Gateway/UserVoiceEvent.cs | 8 +- .../API/Voice/CreatePlainTransportParams.cs | 4 +- .../API/Voice/CreatePlainTransportResponse.cs | 6 +- .../API/Voice/JoinParams.cs | 2 +- .../API/Voice/ProduceParams.cs | 22 +- .../API/Voice/VoiceSocketFrameType.cs | 2 +- .../API/Voice/VoiceSocketRequestFrame.cs | 8 +- .../API/Voice/VoiceSocketResponseFrame.cs | 10 +- src/Kook.Net.WebSocket/AssemblyInfo.cs | 2 +- .../Audio/AudioClient.Events.cs | 4 +- src/Kook.Net.WebSocket/Audio/AudioClient.cs | 61 +- .../Audio/Opus/OpusApplication.cs | 4 +- .../Audio/Opus/OpusConverter.cs | 8 +- src/Kook.Net.WebSocket/Audio/Opus/OpusCtl.cs | 4 +- .../Audio/Opus/OpusDecoder.cs | 6 +- .../Audio/Opus/OpusEncoder.cs | 8 +- .../Audio/Opus/OpusError.cs | 4 +- .../Audio/Opus/OpusSignal.cs | 2 +- .../Audio/Sodium/SecretBox.cs | 4 +- .../Audio/Streams/BufferedWriteStream.cs | 2 +- .../Audio/Streams/InputStream.cs | 2 +- .../Audio/Streams/JitterBuffer.cs | 2 +- .../Audio/Streams/OpusDecodeStream.cs | 4 +- .../Audio/Streams/OpusEncodeStream.cs | 4 +- .../Audio/Streams/OutputStream.cs | 4 +- .../Audio/Streams/RTPReadStream.cs | 10 +- .../Audio/Streams/RTPWriteStream.cs | 4 +- .../Audio/Streams/SodiumDecryptStream.cs | 2 +- .../Audio/Streams/SodiumEncryptStream.cs | 4 +- .../BaseSocketClient.Event.cs | 45 +- src/Kook.Net.WebSocket/BaseSocketClient.cs | 2 +- src/Kook.Net.WebSocket/ClientState.cs | 16 +- .../Commands/SocketCommandContext.cs | 2 +- src/Kook.Net.WebSocket/ConnectionManager.cs | 5 +- .../Entities/Channels/ISocketAudioChannel.cs | 2 +- .../Channels/ISocketMessageChannel.cs | 4 +- .../Channels/ISocketPrivateChannel.cs | 2 +- .../Channels/SocketCategoryChannel.cs | 20 +- .../Entities/Channels/SocketChannel.cs | 20 +- .../Entities/Channels/SocketChannelHelper.cs | 25 +- .../Entities/Channels/SocketDMChannel.cs | 72 +- .../Entities/Channels/SocketGuildChannel.cs | 42 +- .../Entities/Channels/SocketTextChannel.cs | 55 +- .../Entities/Channels/SocketVoiceChannel.cs | 26 +- .../Entities/Guilds/SocketGuild.cs | 82 +- .../Entities/Guilds/SocketGuildHelper.cs | 4 +- .../Entities/Invites/SocketInvite.cs | 8 +- .../Entities/Messages/MessageCache.cs | 12 +- .../Entities/Messages/SocketMessage.cs | 22 +- .../Entities/Messages/SocketMessageHelper.cs | 2 +- .../Entities/Messages/SocketPokeAction.cs | 4 +- .../Entities/Messages/SocketReaction.cs | 4 +- .../Entities/Messages/SocketSystemMessage.cs | 8 +- .../Entities/Messages/SocketUserMessage.cs | 52 +- .../Entities/Roles/SocketRole.cs | 37 +- .../Entities/SocketEntity.cs | 4 +- .../Entities/Users/SocketGlobalUser.cs | 10 +- .../Entities/Users/SocketGuildUser.cs | 40 +- .../Entities/Users/SocketPresence.cs | 6 +- .../Entities/Users/SocketSelfUser.cs | 17 +- .../Entities/Users/SocketUnknownUser.cs | 4 +- .../Entities/Users/SocketUser.cs | 28 +- .../Entities/Users/SocketUserHelper.cs | 6 +- .../Entities/Users/SocketVoiceState.cs | 2 +- .../Extensions/SocketEntityExtensions.cs | 6 +- .../GatewayReconnectException.cs | 2 +- src/Kook.Net.WebSocket/KookSocketApiClient.cs | 34 +- .../KookSocketClient.Events.cs | 4 +- src/Kook.Net.WebSocket/KookSocketClient.cs | 2246 +++++++++-------- src/Kook.Net.WebSocket/KookSocketConfig.cs | 2 +- .../KookSocketRestClient.cs | 4 +- src/Kook.Net.WebSocket/KookVoiceAPIClient.cs | 24 +- .../GatewaySocketFrameTypeConverter.cs | 8 +- .../Net/Converters/MessageTypeConverter.cs | 6 +- .../VoiceSocketFrameTypeConverter.cs | 4 +- .../Net/DefaultUdpSocket.cs | 8 +- .../Net/DefaultUdpSocketProvider.cs | 4 +- .../Net/DefaultWebSocketClient.cs | 17 +- .../Net/DefaultWebSocketClientProvider.cs | 2 +- .../ChannelTests.cs | 20 +- .../Fixtures/KookRestClientFixture.cs | 2 +- .../Fixtures/RestChannelFixture.cs | 4 +- .../Fixtures/RestGuildFixture.cs | 4 +- test/Kook.Net.Tests.Integration/GuildTests.cs | 4 +- .../KookRestApiClientTests.cs | 12 +- .../MessageTests.cs | 10 +- test/Kook.Net.Tests.Integration/RoleTests.cs | 10 +- test/Kook.Net.Tests.Unit/CardBuilderTests.cs | 14 +- .../ChannelPermissionsTests.cs | 2 +- test/Kook.Net.Tests.Unit/ColorTests.cs | 10 +- .../ElementBuilderTests.cs | 60 +- test/Kook.Net.Tests.Unit/EmojiTests.cs | 4 +- test/Kook.Net.Tests.Unit/FormatTests.cs | 2 +- test/Kook.Net.Tests.Unit/GuildHelperTests.cs | 4 +- .../GuildPermissionsTests.cs | 8 +- test/Kook.Net.Tests.Unit/MentionUtilsTests.cs | 2 +- .../Kook.Net.Tests.Unit/MessageHelperTests.cs | 4 +- .../MockedEntities/MockedCategoryChannel.cs | 2 +- .../MockedEntities/MockedDMChannel.cs | 2 +- .../MockedEntities/MockedInvalidChannel.cs | 2 +- .../MockedEntities/MockedTextChannel.cs | 2 +- .../MockedEntities/MockedVoiceChannel.cs | 2 +- .../Kook.Net.Tests.Unit/ModuleBuilderTests.cs | 42 +- .../TimeSpanTypeReaderTests.cs | 2 +- test/Kook.Net.Tests.Unit/TokenUtilsTests.cs | 10 +- test/Kook.Net.Tests.Unit/TypeReaderTests.cs | 2 +- .../Kook.Net.Tests.Unit/UrlValidationTests.cs | 14 +- 640 files changed, 4106 insertions(+), 3816 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..696bb866 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,113 @@ +# EditorConfig is awesome: http://EditorConfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_size = 4 +indent_style = space +trim_trailing_whitespace = true + +[*.{csproj,json,md,nuspec,yml}] +indent_size = 2 +indent_style = space + +[*.{sln,xml}] +indent_style = tab + +[*.cs] +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_property = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_event = false:suggestion + +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion + +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion + +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_var_elsewhere = true:suggestion + +csharp_style_expression_bodied_methods = true:none +csharp_style_expression_bodied_operators = true:none +csharp_style_expression_bodied_properties = true:none +csharp_style_expression_bodied_indexers = true:none +csharp_style_expression_bodied_accessors = true:none + +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion + +csharp_prefer_simple_default_expression = false:none + +csharp_style_throw_expression = true:none +csharp_style_conditional_delegate_call = true:none +csharp_prefer_braces = false:none + +dotnet_sort_system_directives_first = false + +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_within_query_expression_clauses = true + +csharp_indent_case_contents = true +csharp_indent_switch_labels = true +csharp_indent_labels = flush_left + +csharp_space_after_cast = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_method_call_parameter_list_parentheses = false + +csharp_preserve_single_line_statements = false +csharp_preserve_single_line_blocks = true + +dotnet_naming_rule.all_of_const_fields_are_pascal_case.symbols = const_fields +dotnet_naming_rule.all_of_const_fields_are_pascal_case.style = pascal_case +dotnet_naming_rule.all_of_const_fields_are_pascal_case.severity = suggestion + +dotnet_naming_rule.all_of_local_fields_without_const_are_camel_case.symbols = local_fields +dotnet_naming_rule.all_of_local_fields_without_const_are_camel_case.style = starts_with_low_line_camel_case +dotnet_naming_rule.all_of_local_fields_without_const_are_camel_case.severity = suggestion + +dotnet_naming_rule.all_of_interfaces_starts_with_low_line_camel_case.symbols = interfaces +dotnet_naming_rule.all_of_interfaces_starts_with_low_line_camel_case.style = starts_with_i_pascal_case +dotnet_naming_rule.all_of_interfaces_starts_with_low_line_camel_case.severity = suggestion + +dotnet_naming_rule.default_is_pascal_case.symbols = without_interfaces_and_fields +dotnet_naming_rule.default_is_pascal_case.style = pascal_case +dotnet_naming_rule.default_is_pascal_case.severity = suggestion + +dotnet_naming_symbols.const_fields.applicable_kinds = field +dotnet_naming_symbols.const_fields.applicable_accessibilities = * +dotnet_naming_symbols.const_fields.required_modifiers = const + +dotnet_naming_symbols.interfaces.applicable_kinds = interface +dotnet_naming_symbols.interfaces.applicable_accessibilities = * + +dotnet_naming_symbols.local_fields.applicable_kinds = field +dotnet_naming_symbols.local_fields.applicable_accessibilities = internal, private, protected, protected_internal +dotnet_naming_symbols.local_fields.required_modifiers = abstract, must_inherit, readonly, static, shared + +dotnet_naming_symbols.without_interfaces_and_fields.applicable_kinds = class, struct, enum, property, method, event, namespace, delegate, type_parameter +dotnet_naming_symbols.without_interfaces_and_fields.applicable_accessibilities = * + +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.starts_with_i_pascal_case.required_prefix = I +dotnet_naming_style.starts_with_i_pascal_case.capitalization = pascal_case + +dotnet_naming_style.starts_with_low_line_camel_case.required_prefix = _ +dotnet_naming_style.starts_with_low_line_camel_case.capitalization = camel_case diff --git a/samples/Kook.Net.Samples.ReactionRoleBot/Configurations/KookBotConfigurations.cs b/samples/Kook.Net.Samples.ReactionRoleBot/Configurations/KookBotConfigurations.cs index b8286ad3..3a75c84f 100644 --- a/samples/Kook.Net.Samples.ReactionRoleBot/Configurations/KookBotConfigurations.cs +++ b/samples/Kook.Net.Samples.ReactionRoleBot/Configurations/KookBotConfigurations.cs @@ -1,4 +1,4 @@ -using Kook.Net.Samples.ReactionRoleBot.Enums; +using Kook.Net.Samples.ReactionRoleBot.Enums; namespace Kook.Net.Samples.ReactionRoleBot.Configurations; @@ -18,7 +18,7 @@ public class KookBotConfigurations /// 角色ID列表 /// public KookRoles Roles { get; init; } - + /// /// KOOK Bot运行环境 /// @@ -33,4 +33,4 @@ public class KookChannels public class KookRoles { public ulong DeveloperRoleId { get; init; } -} \ No newline at end of file +} diff --git a/samples/Kook.Net.Samples.ReactionRoleBot/Enums/BotEnvironment.cs b/samples/Kook.Net.Samples.ReactionRoleBot/Enums/BotEnvironment.cs index c1b6ff0c..9f49b87b 100644 --- a/samples/Kook.Net.Samples.ReactionRoleBot/Enums/BotEnvironment.cs +++ b/samples/Kook.Net.Samples.ReactionRoleBot/Enums/BotEnvironment.cs @@ -1,4 +1,4 @@ -using System.ComponentModel; +using System.ComponentModel; namespace Kook.Net.Samples.ReactionRoleBot.Enums; @@ -15,4 +15,4 @@ public enum BotEnvironment /// [Description("生产")] Production, -} \ No newline at end of file +} diff --git a/samples/Kook.Net.Samples.ReactionRoleBot/Extensions/KookBotClientExtension.cs b/samples/Kook.Net.Samples.ReactionRoleBot/Extensions/KookBotClientExtension.cs index 680c17f2..04045419 100644 --- a/samples/Kook.Net.Samples.ReactionRoleBot/Extensions/KookBotClientExtension.cs +++ b/samples/Kook.Net.Samples.ReactionRoleBot/Extensions/KookBotClientExtension.cs @@ -74,4 +74,4 @@ public Task StopAsync(CancellationToken cancellationToken) _logger.Fatal("Kook Client Stopped!"); return Task.CompletedTask; } -} \ No newline at end of file +} diff --git a/samples/Kook.Net.Samples.ReactionRoleBot/Extensions/KookBotClientExtensionEventHandlers.cs b/samples/Kook.Net.Samples.ReactionRoleBot/Extensions/KookBotClientExtensionEventHandlers.cs index 8566d924..0055ead9 100644 --- a/samples/Kook.Net.Samples.ReactionRoleBot/Extensions/KookBotClientExtensionEventHandlers.cs +++ b/samples/Kook.Net.Samples.ReactionRoleBot/Extensions/KookBotClientExtensionEventHandlers.cs @@ -6,12 +6,14 @@ public partial class KookBotClientExtension { private async Task ProcessReactionRoleAdd(Cacheable message, Cacheable channel, SocketReaction reaction) { - if (channel.Id != 5770952608991958) return; - if (!reaction.Emote.Equals(Emoji.Parse(":computer:"))) return; - + if (channel.Id != 5770952608991958) + return; + if (!reaction.Emote.Equals(Emoji.Parse(":computer:"))) + return; + SocketRole socketRole = _kookSocketClient.GetGuild(1591057729615250).GetRole(3001653); - SocketGuildUser socketGuildUser = (SocketGuildUser) reaction.User; - + SocketGuildUser socketGuildUser = (SocketGuildUser)reaction.User; + await socketGuildUser.AddRoleAsync(socketRole); SocketDMChannel dmChannel = await socketGuildUser.CreateDMChannelAsync(); @@ -24,21 +26,23 @@ private async Task ProcessReactionRoleAdd(Cacheable message, .WithText($"已在服务器 `{socketGuildUser.Guild.Name}` 内为您授予角色 `{socketRole.Name}`", true)) .AddModule(new ContextModuleBuilder().AddElement(new KMarkdownElementBuilder() .WithContent($"{_kookSocketClient.CurrentUser.Username} | {time}"))); - + await dmChannel.SendCardAsync(builder.Build()); - - _logger.Information("{User}#{IdentifyNumber} is granted {RoleName}", + + _logger.Information("{User}#{IdentifyNumber} is granted {RoleName}", socketGuildUser.Username, socketGuildUser.IdentifyNumber, socketRole.Name); } private async Task ProcessReactionRoleRemove(Cacheable message, Cacheable channel, SocketReaction reaction) { - if (channel.Id != 5770952608991958) return; - if (!reaction.Emote.Equals(Emoji.Parse(":computer:"))) return; - + if (channel.Id != 5770952608991958) + return; + if (!reaction.Emote.Equals(Emoji.Parse(":computer:"))) + return; + SocketRole socketRole = _kookSocketClient.GetGuild(1591057729615250).GetRole(3001653); - SocketGuildUser socketGuildUser = (SocketGuildUser) reaction.User; - + SocketGuildUser socketGuildUser = (SocketGuildUser)reaction.User; + await socketGuildUser.RemoveRoleAsync(socketRole); SocketDMChannel dmChannel = await socketGuildUser.CreateDMChannelAsync(); @@ -51,10 +55,10 @@ private async Task ProcessReactionRoleRemove(Cacheable messa .WithText($"已在服务器 `{socketGuildUser.Guild.Name}` 内为您撤销角色 `{socketRole.Name}`", true)) .AddModule(new ContextModuleBuilder().AddElement(new KMarkdownElementBuilder() .WithContent($"{_kookSocketClient.CurrentUser.Username} | {time}"))); - + await dmChannel.SendCardAsync(builder.Build()); - - _logger.Information("{User}#{IdentifyNumber} is revoked {RoleName}", + + _logger.Information("{User}#{IdentifyNumber} is revoked {RoleName}", socketGuildUser.Username, socketGuildUser.IdentifyNumber, socketRole.Name); } @@ -69,4 +73,4 @@ private async Task SendReactionCard() .SendCardAsync(builder.Build()).ConfigureAwait(false); await _kookSocketClient.Rest.AddReactionAsync(response.Id, Emoji.Parse(":computer:")); } -} \ No newline at end of file +} diff --git a/samples/Kook.Net.Samples.ReactionRoleBot/Program.cs b/samples/Kook.Net.Samples.ReactionRoleBot/Program.cs index edda8cc7..43614014 100644 --- a/samples/Kook.Net.Samples.ReactionRoleBot/Program.cs +++ b/samples/Kook.Net.Samples.ReactionRoleBot/Program.cs @@ -1,4 +1,4 @@ -using Kook; +using Kook; using Kook.Net.Samples.ReactionRoleBot.Configurations; using Kook.Net.Samples.ReactionRoleBot.Extensions; using Kook.WebSocket; @@ -18,7 +18,7 @@ private static async Task Main(string[] args) await host.RunAsync(); } - + private static IHostBuilder CreateHostBuilder(string[] args) { IHostBuilder hostBuilder = Host.CreateDefaultBuilder(args) @@ -72,4 +72,4 @@ private static void ConfigureServices(HostBuilderContext hostContext, IServiceCo .AddHttpClient(); } -} \ No newline at end of file +} diff --git a/samples/Kook.Net.Samples.SimpleBot/Program.cs b/samples/Kook.Net.Samples.SimpleBot/Program.cs index 5d1832da..a44e48a7 100644 --- a/samples/Kook.Net.Samples.SimpleBot/Program.cs +++ b/samples/Kook.Net.Samples.SimpleBot/Program.cs @@ -1,9 +1,9 @@ -// See https://aka.ms/new-console-template for more information +// See https://aka.ms/new-console-template for more information -using System.Collections.Immutable; using Kook; using Kook.Rest; using Kook.WebSocket; +using System.Collections.Immutable; class Program { @@ -102,4 +102,4 @@ public async Task MainAsync() await _client.StartAsync(); await Task.Delay(Timeout.Infinite); } -} \ No newline at end of file +} diff --git a/samples/Kook.Net.Samples.TextCommands/Modules/PublicModule.cs b/samples/Kook.Net.Samples.TextCommands/Modules/PublicModule.cs index c2e8920b..e602fb41 100644 --- a/samples/Kook.Net.Samples.TextCommands/Modules/PublicModule.cs +++ b/samples/Kook.Net.Samples.TextCommands/Modules/PublicModule.cs @@ -1,9 +1,9 @@ using Kook; using Kook.Commands; -using System.IO; -using System.Threading.Tasks; using Kook.Rest; using Kook.WebSocket; +using System.IO; +using System.Threading.Tasks; using TextCommandFramework.Services; namespace TextCommandFramework.Modules; @@ -78,9 +78,9 @@ public Task GuildOnlyCommand() public async Task ModifyCategoryPermissions() { SocketUser contextUser = Context.User; - await ((IGuildChannel) Context.Channel).AddPermissionOverwriteAsync((IGuildUser) Context.User); - await ((SocketChannel) Context.Channel).UpdateAsync(); - await Context.Guild.GetChannel(Context.Channel.Id).ModifyPermissionOverwriteAsync((IGuildUser) Context.User, + await ((IGuildChannel)Context.Channel).AddPermissionOverwriteAsync((IGuildUser)Context.User); + await ((SocketChannel)Context.Channel).UpdateAsync(); + await Context.Guild.GetChannel(Context.Channel.Id).ModifyPermissionOverwriteAsync((IGuildUser)Context.User, permissions => permissions.Modify(viewChannel: PermValue.Allow, sendMessages: PermValue.Deny, attachFiles: PermValue.Allow)); } @@ -92,4 +92,4 @@ public async Task CreateChannel() IReadOnlyCollection readOnlyCollection = guildUserAsync.RoleIds; } -} \ No newline at end of file +} diff --git a/samples/Kook.Net.Samples.TextCommands/Program.cs b/samples/Kook.Net.Samples.TextCommands/Program.cs index 3871acee..54f71f68 100644 --- a/samples/Kook.Net.Samples.TextCommands/Program.cs +++ b/samples/Kook.Net.Samples.TextCommands/Program.cs @@ -70,4 +70,4 @@ private ServiceProvider ConfigureServices() .AddSingleton() .BuildServiceProvider(); } -} \ No newline at end of file +} diff --git a/samples/Kook.Net.Samples.TextCommands/Services/CommandHandlingService.cs b/samples/Kook.Net.Samples.TextCommands/Services/CommandHandlingService.cs index f2767c3c..352349a9 100644 --- a/samples/Kook.Net.Samples.TextCommands/Services/CommandHandlingService.cs +++ b/samples/Kook.Net.Samples.TextCommands/Services/CommandHandlingService.cs @@ -73,4 +73,4 @@ public async Task CommandExecutedAsync(CommandInfo command, ICommandContext cont // the command failed, let's notify the user that something happened. await context.Channel.SendTextAsync($"error: {result}"); } -} \ No newline at end of file +} diff --git a/samples/Kook.Net.Samples.TextCommands/Services/PictureService.cs b/samples/Kook.Net.Samples.TextCommands/Services/PictureService.cs index c7b3d48e..f09d060b 100644 --- a/samples/Kook.Net.Samples.TextCommands/Services/PictureService.cs +++ b/samples/Kook.Net.Samples.TextCommands/Services/PictureService.cs @@ -16,4 +16,4 @@ public async Task GetCatPictureAsync() var resp = await _http.GetAsync("https://cataas.com/cat"); return await resp.Content.ReadAsStreamAsync(); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/AliasAttribute.cs b/src/Kook.Net.Commands/Attributes/AliasAttribute.cs index 2c083ba7..a9c08b2e 100644 --- a/src/Kook.Net.Commands/Attributes/AliasAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/AliasAttribute.cs @@ -37,4 +37,4 @@ public AliasAttribute(params string[] aliases) { Aliases = aliases; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/CommandAttribute.cs b/src/Kook.Net.Commands/Attributes/CommandAttribute.cs index 7dcc7f22..8cd1cd13 100644 --- a/src/Kook.Net.Commands/Attributes/CommandAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/CommandAttribute.cs @@ -37,4 +37,4 @@ public CommandAttribute(string text, bool ignoreExtraArgs) Text = text; IgnoreExtraArgs = ignoreExtraArgs; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/DontAutoLoadAttribute.cs b/src/Kook.Net.Commands/Attributes/DontAutoLoadAttribute.cs index 1f9f6352..13c78060 100644 --- a/src/Kook.Net.Commands/Attributes/DontAutoLoadAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/DontAutoLoadAttribute.cs @@ -13,4 +13,4 @@ namespace Kook.Commands; [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class DontAutoLoadAttribute : Attribute { -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/DontInjectAttribute.cs b/src/Kook.Net.Commands/Attributes/DontInjectAttribute.cs index 8f9e0583..ebf8af42 100644 --- a/src/Kook.Net.Commands/Attributes/DontInjectAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/DontInjectAttribute.cs @@ -27,4 +27,4 @@ namespace Kook.Commands; [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class DontInjectAttribute : Attribute { -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/GroupAttribute.cs b/src/Kook.Net.Commands/Attributes/GroupAttribute.cs index a236f9a7..0db7def7 100644 --- a/src/Kook.Net.Commands/Attributes/GroupAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/GroupAttribute.cs @@ -26,4 +26,4 @@ public GroupAttribute(string prefix) { Prefix = prefix; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/NameAttribute.cs b/src/Kook.Net.Commands/Attributes/NameAttribute.cs index 1ac2b147..4803bacd 100644 --- a/src/Kook.Net.Commands/Attributes/NameAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/NameAttribute.cs @@ -22,4 +22,4 @@ public NameAttribute(string text) { Text = text; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/NamedArgumentTypeAttribute.cs b/src/Kook.Net.Commands/Attributes/NamedArgumentTypeAttribute.cs index f11546a7..88840eee 100644 --- a/src/Kook.Net.Commands/Attributes/NamedArgumentTypeAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/NamedArgumentTypeAttribute.cs @@ -7,4 +7,4 @@ namespace Kook.Commands; /// as a collection of named arguments matching to its properties. /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] -public sealed class NamedArgumentTypeAttribute : Attribute { } \ No newline at end of file +public sealed class NamedArgumentTypeAttribute : Attribute { } diff --git a/src/Kook.Net.Commands/Attributes/OverrideTypeReaderAttribute.cs b/src/Kook.Net.Commands/Attributes/OverrideTypeReaderAttribute.cs index b6a01d85..2fcbb62e 100644 --- a/src/Kook.Net.Commands/Attributes/OverrideTypeReaderAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/OverrideTypeReaderAttribute.cs @@ -43,7 +43,7 @@ public OverrideTypeReaderAttribute(Type overridenTypeReader) { if (!TypeReaderTypeInfo.IsAssignableFrom(overridenTypeReader.GetTypeInfo())) throw new ArgumentException($"{nameof(overridenTypeReader)} must inherit from {nameof(TypeReader)}."); - + TypeReader = overridenTypeReader; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/ParameterPreconditionAttribute.cs b/src/Kook.Net.Commands/Attributes/ParameterPreconditionAttribute.cs index fc0ca439..f7350b5b 100644 --- a/src/Kook.Net.Commands/Attributes/ParameterPreconditionAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/ParameterPreconditionAttribute.cs @@ -18,4 +18,4 @@ public abstract class ParameterPreconditionAttribute : Attribute /// The raw value of the parameter. /// The service collection used for dependency injection. public abstract Task CheckPermissionsAsync(ICommandContext context, ParameterInfo parameter, object value, IServiceProvider services); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/PreconditionAttribute.cs b/src/Kook.Net.Commands/Attributes/PreconditionAttribute.cs index 88f9a975..55d74c75 100644 --- a/src/Kook.Net.Commands/Attributes/PreconditionAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/PreconditionAttribute.cs @@ -35,4 +35,4 @@ public abstract class PreconditionAttribute : Attribute /// The command being executed. /// The service collection used for dependency injection. public abstract Task CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/Preconditions/RequireBotPermissionAttribute.cs b/src/Kook.Net.Commands/Attributes/Preconditions/RequireBotPermissionAttribute.cs index 1167cd0e..5a523347 100644 --- a/src/Kook.Net.Commands/Attributes/Preconditions/RequireBotPermissionAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/Preconditions/RequireBotPermissionAttribute.cs @@ -82,4 +82,4 @@ public override async Task CheckPermissionsAsync(ICommandCon return PreconditionResult.FromSuccess(); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/Preconditions/RequireContextAttribute.cs b/src/Kook.Net.Commands/Attributes/Preconditions/RequireContextAttribute.cs index bd4e30b5..8c49cb16 100644 --- a/src/Kook.Net.Commands/Attributes/Preconditions/RequireContextAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/Preconditions/RequireContextAttribute.cs @@ -64,4 +64,4 @@ public override Task CheckPermissionsAsync(ICommandContext c else return Task.FromResult(PreconditionResult.FromError(ErrorMessage ?? $"Invalid context for command; accepted contexts: {Contexts}.")); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserAttribute.cs b/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserAttribute.cs index 4ba7b7ad..f845fd76 100644 --- a/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserAttribute.cs @@ -32,7 +32,7 @@ namespace Kook.Commands; public class RequireUserAttribute : PreconditionAttribute { private readonly ulong _userId; - + public RequireUserAttribute(ulong userId) { _userId = userId; @@ -42,7 +42,7 @@ public RequireUserAttribute(IUser user) { _userId = user.Id; } - + /// public override string ErrorMessage { get; set; } @@ -53,4 +53,4 @@ public override Task CheckPermissionsAsync(ICommandContext c ? PreconditionResult.FromError(ErrorMessage ?? $"Command can only be run by the specified user with identifier {_userId}.") : PreconditionResult.FromSuccess()); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserPermissionAttribute.cs b/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserPermissionAttribute.cs index 974fb560..280a705f 100644 --- a/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserPermissionAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/Preconditions/RequireUserPermissionAttribute.cs @@ -61,7 +61,7 @@ public override Task CheckPermissionsAsync(ICommandContext c if (GuildPermission.HasValue) { if (guildUser == null) - return Task.FromResult(PreconditionResult.FromError(NotAGuildErrorMessage ?? "Command must be used in a guild channel.")); + return Task.FromResult(PreconditionResult.FromError(NotAGuildErrorMessage ?? "Command must be used in a guild channel.")); if (!guildUser.GuildPermissions.Has(GuildPermission.Value)) return Task.FromResult(PreconditionResult.FromError(ErrorMessage ?? $"User requires guild permission {GuildPermission.Value}.")); } @@ -80,4 +80,4 @@ public override Task CheckPermissionsAsync(ICommandContext c return Task.FromResult(PreconditionResult.FromSuccess()); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/PriorityAttribute.cs b/src/Kook.Net.Commands/Attributes/PriorityAttribute.cs index f8a06319..a0794dcb 100644 --- a/src/Kook.Net.Commands/Attributes/PriorityAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/PriorityAttribute.cs @@ -20,4 +20,4 @@ public PriorityAttribute(int priority) { Priority = priority; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/RemainderAttribute.cs b/src/Kook.Net.Commands/Attributes/RemainderAttribute.cs index bca45c82..6c4b2c5d 100644 --- a/src/Kook.Net.Commands/Attributes/RemainderAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/RemainderAttribute.cs @@ -8,4 +8,4 @@ namespace Kook.Commands; [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public class RemainderAttribute : Attribute { -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/RemarksAttribute.cs b/src/Kook.Net.Commands/Attributes/RemarksAttribute.cs index bc491636..8fb85392 100644 --- a/src/Kook.Net.Commands/Attributes/RemarksAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/RemarksAttribute.cs @@ -15,4 +15,4 @@ public RemarksAttribute(string text) { Text = text; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Attributes/SummaryAttribute.cs b/src/Kook.Net.Commands/Attributes/SummaryAttribute.cs index c21c6429..778e6c36 100644 --- a/src/Kook.Net.Commands/Attributes/SummaryAttribute.cs +++ b/src/Kook.Net.Commands/Attributes/SummaryAttribute.cs @@ -15,4 +15,4 @@ public SummaryAttribute(string text) { Text = text; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Builders/CommandBuilder.cs b/src/Kook.Net.Commands/Builders/CommandBuilder.cs index 4a91a88f..b9077c61 100644 --- a/src/Kook.Net.Commands/Builders/CommandBuilder.cs +++ b/src/Kook.Net.Commands/Builders/CommandBuilder.cs @@ -1,7 +1,7 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using System.Collections.Generic; namespace Kook.Commands.Builders; @@ -145,4 +145,4 @@ internal CommandInfo Build(ModuleInfo info, CommandService service) return new CommandInfo(this, info, service); } #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Builders/ModuleBuilder.cs b/src/Kook.Net.Commands/Builders/ModuleBuilder.cs index 4c4a0512..ff5b8b81 100644 --- a/src/Kook.Net.Commands/Builders/ModuleBuilder.cs +++ b/src/Kook.Net.Commands/Builders/ModuleBuilder.cs @@ -20,7 +20,9 @@ public class ModuleBuilder public string Name { get; set; } public string Summary { get; set; } public string Remarks { get; set; } - public string Group { get => _group; + public string Group + { + get => _group; set { _aliases.Remove(_group); @@ -145,4 +147,4 @@ private ModuleInfo BuildImpl(CommandService service, IServiceProvider services, internal ModuleInfo Build(CommandService service, IServiceProvider services, ModuleInfo parent) => BuildImpl(service, services, parent); #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Builders/ModuleClassBuilder.cs b/src/Kook.Net.Commands/Builders/ModuleClassBuilder.cs index f17b5652..aab36fa6 100644 --- a/src/Kook.Net.Commands/Builders/ModuleClassBuilder.cs +++ b/src/Kook.Net.Commands/Builders/ModuleClassBuilder.cs @@ -1,11 +1,10 @@ +using Kook.Commands.Builders; using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using System.Reflection; using System.Threading.Tasks; -using Kook.Commands.Builders; - namespace Kook.Commands; internal static class ModuleClassBuilder @@ -80,11 +79,11 @@ private static void BuildSubTypes(ModuleBuilder builder, IEnumerable s { if (!IsValidModuleDefinition(typeInfo)) continue; - + if (builtTypes.Contains(typeInfo)) continue; - - builder.AddModule((module) => + + builder.AddModule((module) => { BuildModule(module, typeInfo, service, services); BuildSubTypes(module, typeInfo.DeclaredNestedTypes, builtTypes, service, services); @@ -139,7 +138,7 @@ private static void BuildModule(ModuleBuilder builder, TypeInfo typeInfo, Comman foreach (var method in validCommands) { - builder.AddCommand((command) => + builder.AddCommand((command) => { BuildCommand(command, typeInfo, method, service, services); }); @@ -149,7 +148,7 @@ private static void BuildModule(ModuleBuilder builder, TypeInfo typeInfo, Comman private static void BuildCommand(CommandBuilder builder, TypeInfo typeInfo, MethodInfo method, CommandService service, IServiceProvider serviceprovider) { var attributes = method.GetCustomAttributes(); - + foreach (var attribute in attributes) { switch (attribute) @@ -191,7 +190,7 @@ private static void BuildCommand(CommandBuilder builder, TypeInfo typeInfo, Meth int pos = 0, count = parameters.Length; foreach (var paramInfo in parameters) { - builder.AddParameter((parameter) => + builder.AddParameter((parameter) => { BuildParameter(parameter, paramInfo, pos++, count, service, serviceprovider); }); @@ -313,4 +312,4 @@ private static bool IsValidCommandDefinition(MethodInfo methodInfo) !methodInfo.IsStatic && !methodInfo.IsGenericMethod; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Builders/ParameterBuilder.cs b/src/Kook.Net.Commands/Builders/ParameterBuilder.cs index e5dba641..c715b82f 100644 --- a/src/Kook.Net.Commands/Builders/ParameterBuilder.cs +++ b/src/Kook.Net.Commands/Builders/ParameterBuilder.cs @@ -1,9 +1,8 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Reflection; -using System.Collections.Generic; - namespace Kook.Commands.Builders; public class ParameterBuilder @@ -137,4 +136,4 @@ internal ParameterInfo Build(CommandInfo info) return new ParameterInfo(this, info, Command.Module.Service); } #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/CommandContext.cs b/src/Kook.Net.Commands/CommandContext.cs index df401aa6..5d200f05 100644 --- a/src/Kook.Net.Commands/CommandContext.cs +++ b/src/Kook.Net.Commands/CommandContext.cs @@ -30,4 +30,4 @@ public CommandContext(IKookClient client, IUserMessage msg) User = msg.Author; Message = msg; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/CommandError.cs b/src/Kook.Net.Commands/CommandError.cs index 0e180a91..1055f115 100644 --- a/src/Kook.Net.Commands/CommandError.cs +++ b/src/Kook.Net.Commands/CommandError.cs @@ -47,4 +47,4 @@ public enum CommandError /// Thrown when the command is not successfully executed on runtime. /// Unsuccessful -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/CommandException.cs b/src/Kook.Net.Commands/CommandException.cs index b3bfb3df..c771968a 100644 --- a/src/Kook.Net.Commands/CommandException.cs +++ b/src/Kook.Net.Commands/CommandException.cs @@ -26,4 +26,4 @@ public CommandException(CommandInfo command, ICommandContext context, Exception Command = command; Context = context; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/CommandMatch.cs b/src/Kook.Net.Commands/CommandMatch.cs index 3947fcb1..3197e944 100644 --- a/src/Kook.Net.Commands/CommandMatch.cs +++ b/src/Kook.Net.Commands/CommandMatch.cs @@ -25,4 +25,4 @@ public Task ExecuteAsync(ICommandContext context, IEnumerable a => Command.ExecuteAsync(context, argList, paramList, services); public Task ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services) => Command.ExecuteAsync(context, parseResult, services); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/CommandParser.cs b/src/Kook.Net.Commands/CommandParser.cs index e7a5a5dc..70a812f5 100644 --- a/src/Kook.Net.Commands/CommandParser.cs +++ b/src/Kook.Net.Commands/CommandParser.cs @@ -194,4 +194,4 @@ static char GetMatch(IReadOnlyDictionary dict, char ch) return ParseResult.FromSuccess(argList.ToImmutable(), paramList.ToImmutable()); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/CommandService.cs b/src/Kook.Net.Commands/CommandService.cs index 575b9e98..c0516687 100644 --- a/src/Kook.Net.Commands/CommandService.cs +++ b/src/Kook.Net.Commands/CommandService.cs @@ -1,3 +1,5 @@ +using Kook.Commands.Builders; +using Kook.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -6,8 +8,6 @@ using System.Reflection; using System.Threading; using System.Threading.Tasks; -using Kook.Commands.Builders; -using Kook.Logging; namespace Kook.Commands; @@ -648,7 +648,7 @@ public async Task ValidateAndGetBestMatch(SearchResult matches, IComman var bestCandidate = preconditionResults .OrderByDescending(x => x.Key.Command.Priority) .FirstOrDefault(x => !x.Value.IsSuccess); - return MatchResult.FromSuccess(bestCandidate.Key,bestCandidate.Value); + return MatchResult.FromSuccess(bestCandidate.Key, bestCandidate.Value); } var parseResults = new Dictionary(); @@ -678,7 +678,7 @@ public async Task ValidateAndGetBestMatch(SearchResult matches, IComman .Where(x => x.Value.IsSuccess) .ToArray(); - if(successfulParses.Length == 0) + if (successfulParses.Length == 0) { var bestMatch = parseResults .FirstOrDefault(x => !x.Value.IsSuccess); @@ -711,4 +711,4 @@ void IDisposable.Dispose() Dispose(true); } #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/CommandServiceConfig.cs b/src/Kook.Net.Commands/CommandServiceConfig.cs index b0167c2e..89fb50f3 100644 --- a/src/Kook.Net.Commands/CommandServiceConfig.cs +++ b/src/Kook.Net.Commands/CommandServiceConfig.cs @@ -17,7 +17,7 @@ public class CommandServiceConfig /// Gets or sets the that separates an argument with another. /// public char SeparatorChar { get; set; } = ' '; - + /// /// Gets or sets whether commands should be case-sensitive. /// @@ -58,4 +58,4 @@ public class CommandServiceConfig /// Gets or sets a value that indicates whether extra parameters should be ignored. /// public bool IgnoreExtraArgs { get; set; } = false; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/EmptyServiceProvider.cs b/src/Kook.Net.Commands/EmptyServiceProvider.cs index d775e1cd..a37962d7 100644 --- a/src/Kook.Net.Commands/EmptyServiceProvider.cs +++ b/src/Kook.Net.Commands/EmptyServiceProvider.cs @@ -5,6 +5,6 @@ namespace Kook.Commands; internal class EmptyServiceProvider : IServiceProvider { public static readonly EmptyServiceProvider Instance = new EmptyServiceProvider(); - + public object GetService(Type serviceType) => null; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Extensions/CommandServiceExtensions.cs b/src/Kook.Net.Commands/Extensions/CommandServiceExtensions.cs index 00ee6bcb..a3fb0000 100644 --- a/src/Kook.Net.Commands/Extensions/CommandServiceExtensions.cs +++ b/src/Kook.Net.Commands/Extensions/CommandServiceExtensions.cs @@ -72,4 +72,4 @@ public static async Task> GetExecutableCommands return executableCommands; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Extensions/IEnumerableExtensions.cs b/src/Kook.Net.Commands/Extensions/IEnumerableExtensions.cs index 69885a35..598b68bc 100644 --- a/src/Kook.Net.Commands/Extensions/IEnumerableExtensions.cs +++ b/src/Kook.Net.Commands/Extensions/IEnumerableExtensions.cs @@ -18,4 +18,4 @@ public static IEnumerable Permutate( } } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Extensions/MessageExtensions.cs b/src/Kook.Net.Commands/Extensions/MessageExtensions.cs index 4f4a345b..7b6536ca 100644 --- a/src/Kook.Net.Commands/Extensions/MessageExtensions.cs +++ b/src/Kook.Net.Commands/Extensions/MessageExtensions.cs @@ -47,14 +47,18 @@ public static bool HasMentionPrefix(this IUserMessage msg, IUser user, ref int a if (msg.Type == MessageType.Text) { var text = msg.Content; - if (string.IsNullOrEmpty(text) || text.Length <= 6 || text[0] != '@') return false; + if (string.IsNullOrEmpty(text) || text.Length <= 6 || text[0] != '@') + return false; int endPos = text.IndexOf('#'); - if (endPos == -1) return false; + if (endPos == -1) + return false; endPos += 4; - if (text.Length < endPos + 2 || text[endPos + 1] != ' ') return false; + if (text.Length < endPos + 2 || text[endPos + 1] != ' ') + return false; - if (!MentionUtils.TryParseUser(text.Substring(0, endPos + 1), out ulong userId, TagMode.PlainText)) return false; + if (!MentionUtils.TryParseUser(text.Substring(0, endPos + 1), out ulong userId, TagMode.PlainText)) + return false; if (userId == user.Id) { argPos = endPos + 2; @@ -65,24 +69,28 @@ public static bool HasMentionPrefix(this IUserMessage msg, IUser user, ref int a { var text = msg.Content; #if NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER - if (string.IsNullOrEmpty(text) || text.Length <= 10 || text[..5] != "(met)") return false; + if (string.IsNullOrEmpty(text) || text.Length <= 10 || text[..5] != "(met)") + return false; #else if (string.IsNullOrEmpty(text) || text.Length <= 10 || text.Substring(0, 5) != "(met)") return false; #endif int endPos = text.IndexOf("(met)", 5, StringComparison.Ordinal); - if (endPos == -1) return false; + if (endPos == -1) + return false; endPos += 4; - if (text.Length < endPos + 2 || text[endPos + 1] != ' ') return false; + if (text.Length < endPos + 2 || text[endPos + 1] != ' ') + return false; - if (!MentionUtils.TryParseUser(text.Substring(0, endPos + 1), out ulong userId, TagMode.KMarkdown)) return false; + if (!MentionUtils.TryParseUser(text.Substring(0, endPos + 1), out ulong userId, TagMode.KMarkdown)) + return false; if (userId == user.Id) { argPos = endPos + 2; return true; } } - + return false; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/IModuleBase.cs b/src/Kook.Net.Commands/IModuleBase.cs index 09cdb2be..e6c54b76 100644 --- a/src/Kook.Net.Commands/IModuleBase.cs +++ b/src/Kook.Net.Commands/IModuleBase.cs @@ -18,7 +18,7 @@ public interface IModuleBase /// /// The command thats about to run. Task BeforeExecuteAsync(CommandInfo command); - + /// /// Executed before a command is run in this module base. /// @@ -43,4 +43,4 @@ public interface IModuleBase /// The command service that is building this module. /// The builder constructing this module. void OnModuleBuilding(CommandService commandService, ModuleBuilder builder); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Info/CommandInfo.cs b/src/Kook.Net.Commands/Info/CommandInfo.cs index 3ef5c9b3..23f778f0 100644 --- a/src/Kook.Net.Commands/Info/CommandInfo.cs +++ b/src/Kook.Net.Commands/Info/CommandInfo.cs @@ -1,8 +1,8 @@ using Kook.Commands.Builders; using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; -using System.Collections.Concurrent; using System.Diagnostics; using System.Linq; using System.Reflection; @@ -175,7 +175,7 @@ public async Task ParseAsync(ICommandContext context, int startInde return await CommandParser.ParseArgsAsync(this, context, _commandService._ignoreExtraArgs, services, input, 0, _commandService._quotationMarkAliasMap).ConfigureAwait(false); } - + public Task ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services) { if (!parseResult.IsSuccess) @@ -335,4 +335,4 @@ internal string GetLogText(ICommandContext context) else return $"\"{Name}\" for {context.User} in {context.Channel}"; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Info/ModuleInfo.cs b/src/Kook.Net.Commands/Info/ModuleInfo.cs index 2a28fc4a..f3f82fa3 100644 --- a/src/Kook.Net.Commands/Info/ModuleInfo.cs +++ b/src/Kook.Net.Commands/Info/ModuleInfo.cs @@ -1,8 +1,8 @@ +using Kook.Commands.Builders; using System; -using System.Linq; using System.Collections.Generic; using System.Collections.Immutable; -using Kook.Commands.Builders; +using System.Linq; namespace Kook.Commands; @@ -143,4 +143,4 @@ private static List BuildAttributes(ModuleBuilder builder) return result; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Info/ParameterInfo.cs b/src/Kook.Net.Commands/Info/ParameterInfo.cs index 2a511b32..0df150e9 100644 --- a/src/Kook.Net.Commands/Info/ParameterInfo.cs +++ b/src/Kook.Net.Commands/Info/ParameterInfo.cs @@ -95,4 +95,4 @@ public async Task ParseAsync(ICommandContext context, string i public override string ToString() => Name; private string DebuggerDisplay => $"{Name}{(IsOptional ? " (Optional)" : "")}{(IsRemainder ? " (Remainder)" : "")}"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Map/CommandMap.cs b/src/Kook.Net.Commands/Map/CommandMap.cs index 9886dd4f..5ded0b6c 100644 --- a/src/Kook.Net.Commands/Map/CommandMap.cs +++ b/src/Kook.Net.Commands/Map/CommandMap.cs @@ -29,4 +29,4 @@ public IEnumerable GetCommands(string text) { return _root.GetCommands(_service, text, 0, text != ""); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Map/CommandMapNode.cs b/src/Kook.Net.Commands/Map/CommandMapNode.cs index 9d116c90..8bb548fe 100644 --- a/src/Kook.Net.Commands/Map/CommandMapNode.cs +++ b/src/Kook.Net.Commands/Map/CommandMapNode.cs @@ -131,4 +131,4 @@ private static int NextSegment(string text, int startIndex, char[] separators, c } return (lowest != int.MaxValue) ? lowest : -1; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/ModuleBase.cs b/src/Kook.Net.Commands/ModuleBase.cs index b6573bc9..34e31d10 100644 --- a/src/Kook.Net.Commands/ModuleBase.cs +++ b/src/Kook.Net.Commands/ModuleBase.cs @@ -1,6 +1,6 @@ +using Kook.Commands.Builders; using System; using System.Threading.Tasks; -using Kook.Commands.Builders; namespace Kook.Commands; @@ -41,7 +41,7 @@ public abstract class ModuleBase : IModuleBase /// true if the message to be sent can be seen only by the command invoker; otherwise, false. /// /// The request options for this request. - protected virtual async Task> ReplyFileAsync(string path, string fileName = null, + protected virtual async Task> ReplyFileAsync(string path, string fileName = null, AttachmentType type = AttachmentType.File, bool isQuote = true, bool isEphemeral = false, RequestOptions options = null) { return await Context.Channel.SendFileAsync(path, fileName, type, isQuote ? new Quote(Context.Message.Id) : null, @@ -88,7 +88,7 @@ protected virtual async Task> ReplyFileAsync(FileA return await Context.Channel.SendFileAsync(attachment, isQuote ? new Quote(Context.Message.Id) : null, isEphemeral ? Context.User : null, options).ConfigureAwait(false); } - + /// /// Sends a text message to the source channel. /// @@ -108,7 +108,7 @@ protected virtual async Task> ReplyTextAsync(strin return await Context.Channel.SendTextAsync(message, isQuote ? new Quote(Context.Message.Id) : null, isEphemeral ? Context.User : null, options).ConfigureAwait(false); } - + /// /// Sends a card message to the source channel. /// @@ -196,4 +196,4 @@ void IModuleBase.SetContext(ICommandContext context) void IModuleBase.AfterExecute(CommandInfo command) => AfterExecute(command); void IModuleBase.OnModuleBuilding(CommandService commandService, ModuleBuilder builder) => OnModuleBuilding(commandService, builder); #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/MultiMatchHandling.cs b/src/Kook.Net.Commands/MultiMatchHandling.cs index eee9a0f5..a35ba41e 100644 --- a/src/Kook.Net.Commands/MultiMatchHandling.cs +++ b/src/Kook.Net.Commands/MultiMatchHandling.cs @@ -9,4 +9,4 @@ public enum MultiMatchHandling Exception, /// Indicates that when multiple results are found, the best result should be chosen. Best -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/PrimitiveParsers.cs b/src/Kook.Net.Commands/PrimitiveParsers.cs index a1488f9f..26285ab4 100644 --- a/src/Kook.Net.Commands/PrimitiveParsers.cs +++ b/src/Kook.Net.Commands/PrimitiveParsers.cs @@ -36,4 +36,4 @@ static IReadOnlyDictionary CreateParsers() public static TryParseDelegate Get() => (TryParseDelegate)Parsers.Value[typeof(T)]; public static Delegate Get(Type type) => Parsers.Value[type]; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Readers/ChannelTypeReader.cs b/src/Kook.Net.Commands/Readers/ChannelTypeReader.cs index 439e47b5..078145e1 100644 --- a/src/Kook.Net.Commands/Readers/ChannelTypeReader.cs +++ b/src/Kook.Net.Commands/Readers/ChannelTypeReader.cs @@ -31,7 +31,7 @@ public override async Task ReadAsync(ICommandContext context, MessageType.Text => TagMode.PlainText, MessageType.KMarkdown => TagMode.KMarkdown, _ => throw new ArgumentOutOfRangeException(nameof(context.Message.Type)) - + }; //By Mention (1.0) if (MentionUtils.TryParseChannel(input, out ulong id, tagMode)) @@ -57,4 +57,4 @@ private void AddResult(Dictionary results, T channel, fl if (channel != null && !results.ContainsKey(channel.Id)) results.Add(channel.Id, new TypeReaderValue(channel, score)); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Readers/EnumTypeReader.cs b/src/Kook.Net.Commands/Readers/EnumTypeReader.cs index de29f6db..1bf4cc2b 100644 --- a/src/Kook.Net.Commands/Readers/EnumTypeReader.cs +++ b/src/Kook.Net.Commands/Readers/EnumTypeReader.cs @@ -23,7 +23,7 @@ internal class EnumTypeReader : TypeReader private readonly IReadOnlyDictionary _enumsByValue; private readonly Type _enumType; private readonly TryParseDelegate _tryParse; - + public EnumTypeReader(Type type, TryParseDelegate parser) { _enumType = type; @@ -33,7 +33,7 @@ public EnumTypeReader(Type type, TryParseDelegate parser) var byValueBuilder = ImmutableDictionary.CreateBuilder(); foreach (var v in Enum.GetNames(_enumType)) - { + { var parsedValue = Enum.Parse(_enumType, v); byNameBuilder.Add(v.ToLower(), parsedValue); if (!byValueBuilder.ContainsKey((T)parsedValue)) @@ -64,4 +64,4 @@ public override Task ReadAsync(ICommandContext context, string return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, $"Value is not a {_enumType.Name}.")); } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Readers/MessageTypeReader.cs b/src/Kook.Net.Commands/Readers/MessageTypeReader.cs index 9c395fe0..da8283a0 100644 --- a/src/Kook.Net.Commands/Readers/MessageTypeReader.cs +++ b/src/Kook.Net.Commands/Readers/MessageTypeReader.cs @@ -23,4 +23,4 @@ public override async Task ReadAsync(ICommandContext context, return TypeReaderResult.FromError(CommandError.ObjectNotFound, "Message not found."); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Readers/NamedArgumentTypeReader.cs b/src/Kook.Net.Commands/Readers/NamedArgumentTypeReader.cs index b9100291..74bd3469 100644 --- a/src/Kook.Net.Commands/Readers/NamedArgumentTypeReader.cs +++ b/src/Kook.Net.Commands/Readers/NamedArgumentTypeReader.cs @@ -116,7 +116,7 @@ PropertyInfo GetPropAndValue(out string argv) argv = input.Substring(beginRead + 1, currentRead - beginRead - 1).Trim(); currentRead++; } - else + else argv = input.Substring(beginRead, currentRead - beginRead); return _tProps[currentParam]; @@ -186,4 +186,4 @@ private enum ReadState InQuotedArgument, End } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Readers/NullableTypeReader.cs b/src/Kook.Net.Commands/Readers/NullableTypeReader.cs index 4d473d38..554f8b24 100644 --- a/src/Kook.Net.Commands/Readers/NullableTypeReader.cs +++ b/src/Kook.Net.Commands/Readers/NullableTypeReader.cs @@ -31,4 +31,4 @@ public override async Task ReadAsync(ICommandContext context, return TypeReaderResult.FromSuccess(new T?()); return await _baseTypeReader.ReadAsync(context, input, services).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Readers/PrimitiveTypeReader.cs b/src/Kook.Net.Commands/Readers/PrimitiveTypeReader.cs index aff743e3..a02a2d73 100644 --- a/src/Kook.Net.Commands/Readers/PrimitiveTypeReader.cs +++ b/src/Kook.Net.Commands/Readers/PrimitiveTypeReader.cs @@ -38,4 +38,4 @@ public override Task ReadAsync(ICommandContext context, string return Task.FromResult(TypeReaderResult.FromSuccess(new TypeReaderValue(value, _score))); return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, $"Failed to parse {typeof(T).Name}.")); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Readers/RoleTypeReader.cs b/src/Kook.Net.Commands/Readers/RoleTypeReader.cs index e4ee6d86..d53fd191 100644 --- a/src/Kook.Net.Commands/Readers/RoleTypeReader.cs +++ b/src/Kook.Net.Commands/Readers/RoleTypeReader.cs @@ -25,7 +25,7 @@ public override Task ReadAsync(ICommandContext context, string MessageType.Text => TagMode.PlainText, MessageType.KMarkdown => TagMode.KMarkdown, _ => throw new ArgumentOutOfRangeException(nameof(context.Message.Type)) - + }; //By Mention (1.0) @@ -51,4 +51,4 @@ private void AddResult(Dictionary results, T role, float if (role != null && !results.ContainsKey(role.Id)) results.Add(role.Id, new TypeReaderValue(role, score)); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Readers/TimeSpanTypeReader.cs b/src/Kook.Net.Commands/Readers/TimeSpanTypeReader.cs index f195bb03..0d7223a2 100644 --- a/src/Kook.Net.Commands/Readers/TimeSpanTypeReader.cs +++ b/src/Kook.Net.Commands/Readers/TimeSpanTypeReader.cs @@ -51,4 +51,4 @@ public override Task ReadAsync(ICommandContext context, string return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Failed to parse TimeSpan")); } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Readers/TypeReader.cs b/src/Kook.Net.Commands/Readers/TypeReader.cs index 73ab26f8..b2447d58 100644 --- a/src/Kook.Net.Commands/Readers/TypeReader.cs +++ b/src/Kook.Net.Commands/Readers/TypeReader.cs @@ -18,4 +18,4 @@ public abstract class TypeReader /// A task that represents the asynchronous parsing operation. The task result contains the parsing result. /// public abstract Task ReadAsync(ICommandContext context, string input, IServiceProvider services); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Readers/UserTypeReader.cs b/src/Kook.Net.Commands/Readers/UserTypeReader.cs index e2f4cddb..99946cde 100644 --- a/src/Kook.Net.Commands/Readers/UserTypeReader.cs +++ b/src/Kook.Net.Commands/Readers/UserTypeReader.cs @@ -25,7 +25,7 @@ public override async Task ReadAsync(ICommandContext context, MessageType.Text => TagMode.PlainText, MessageType.KMarkdown => TagMode.KMarkdown, _ => throw new ArgumentOutOfRangeException(nameof(context.Message.Type)) - + }; if (context.Guild != null) @@ -72,7 +72,7 @@ await channelUsers .Where(x => string.Equals(input, x.Username, StringComparison.OrdinalIgnoreCase)) .ForEachAsync(channelUser => AddResult(results, channelUser as T, channelUser.Username == input ? 0.65f : 0.55f)) .ConfigureAwait(false); - + foreach (var guildUser in guildUsers.Where(x => string.Equals(input, x.Username, StringComparison.OrdinalIgnoreCase))) AddResult(results, guildUser as T, guildUser.Username == input ? 0.60f : 0.50f); } @@ -98,4 +98,4 @@ private void AddResult(Dictionary results, T user, float if (user != null && !results.ContainsKey(user.Id)) results.Add(user.Id, new TypeReaderValue(user, score)); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Results/ExecuteResult.cs b/src/Kook.Net.Commands/Results/ExecuteResult.cs index 125f32b0..263a9dce 100644 --- a/src/Kook.Net.Commands/Results/ExecuteResult.cs +++ b/src/Kook.Net.Commands/Results/ExecuteResult.cs @@ -81,4 +81,4 @@ public static ExecuteResult FromError(IResult result) /// public override string ToString() => IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; private string DebuggerDisplay => IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Results/IResult.cs b/src/Kook.Net.Commands/Results/IResult.cs index a14a0f24..13f61072 100644 --- a/src/Kook.Net.Commands/Results/IResult.cs +++ b/src/Kook.Net.Commands/Results/IResult.cs @@ -27,4 +27,4 @@ public interface IResult /// true if the result is positive; otherwise false. /// bool IsSuccess { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Results/MatchResult.cs b/src/Kook.Net.Commands/Results/MatchResult.cs index 74c2c9a7..ebb98d74 100644 --- a/src/Kook.Net.Commands/Results/MatchResult.cs +++ b/src/Kook.Net.Commands/Results/MatchResult.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Kook.Commands; @@ -30,7 +30,7 @@ private MatchResult(CommandMatch? match, IResult pipeline, CommandError? error, } public static MatchResult FromSuccess(CommandMatch match, IResult pipeline) - => new MatchResult(match,pipeline,null, null); + => new MatchResult(match, pipeline, null, null); public static MatchResult FromError(CommandError error, string reason) => new MatchResult(null, null, error, reason); public static MatchResult FromError(Exception ex) @@ -43,4 +43,4 @@ public static MatchResult FromError(IResult pipeline, CommandError error, string public override string ToString() => IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; private string DebuggerDisplay => IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Results/ParseResult.cs b/src/Kook.Net.Commands/Results/ParseResult.cs index 434e848b..954785dc 100644 --- a/src/Kook.Net.Commands/Results/ParseResult.cs +++ b/src/Kook.Net.Commands/Results/ParseResult.cs @@ -81,4 +81,4 @@ public static ParseResult FromError(IResult result, ParameterInfo parameterInfo) public override string ToString() => IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; private string DebuggerDisplay => IsSuccess ? $"Success ({ArgValues.Count}{(ParamValues.Count > 0 ? $" +{ParamValues.Count} Values" : "")})" : $"{Error}: {ErrorReason}"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Results/PreconditionGroupResult.cs b/src/Kook.Net.Commands/Results/PreconditionGroupResult.cs index 06d16517..e5a50afc 100644 --- a/src/Kook.Net.Commands/Results/PreconditionGroupResult.cs +++ b/src/Kook.Net.Commands/Results/PreconditionGroupResult.cs @@ -26,4 +26,4 @@ public static PreconditionGroupResult FromError(string reason, ICollection IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; private string DebuggerDisplay => IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Results/PreconditionResult.cs b/src/Kook.Net.Commands/Results/PreconditionResult.cs index e722cd85..363191e7 100644 --- a/src/Kook.Net.Commands/Results/PreconditionResult.cs +++ b/src/Kook.Net.Commands/Results/PreconditionResult.cs @@ -55,4 +55,4 @@ public static PreconditionResult FromError(IResult result) /// public override string ToString() => IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; private string DebuggerDisplay => IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Results/RuntimeResult.cs b/src/Kook.Net.Commands/Results/RuntimeResult.cs index 76c7613e..c50aec74 100644 --- a/src/Kook.Net.Commands/Results/RuntimeResult.cs +++ b/src/Kook.Net.Commands/Results/RuntimeResult.cs @@ -29,4 +29,4 @@ protected RuntimeResult(CommandError? error, string reason) public override string ToString() => Reason ?? (IsSuccess ? "Successful" : "Unsuccessful"); private string DebuggerDisplay => IsSuccess ? $"Success: {Reason ?? "No Reason"}" : $"{Error}: {Reason}"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Results/SearchResult.cs b/src/Kook.Net.Commands/Results/SearchResult.cs index f8a8d057..9bd27db4 100644 --- a/src/Kook.Net.Commands/Results/SearchResult.cs +++ b/src/Kook.Net.Commands/Results/SearchResult.cs @@ -37,4 +37,4 @@ public static SearchResult FromError(IResult result) public override string ToString() => IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; private string DebuggerDisplay => IsSuccess ? $"Success ({Commands.Count} Results)" : $"{Error}: {ErrorReason}"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Results/TypeReaderResult.cs b/src/Kook.Net.Commands/Results/TypeReaderResult.cs index b4cd9cd1..4bf26bc6 100644 --- a/src/Kook.Net.Commands/Results/TypeReaderResult.cs +++ b/src/Kook.Net.Commands/Results/TypeReaderResult.cs @@ -62,4 +62,4 @@ public static TypeReaderResult FromError(IResult result) public override string ToString() => IsSuccess ? "Success" : $"{Error}: {ErrorReason}"; private string DebuggerDisplay => IsSuccess ? $"Success ({string.Join(", ", Values)})" : $"{Error}: {ErrorReason}"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/RunMode.cs b/src/Kook.Net.Commands/RunMode.cs index 2b7fec4f..c95927ad 100644 --- a/src/Kook.Net.Commands/RunMode.cs +++ b/src/Kook.Net.Commands/RunMode.cs @@ -19,4 +19,4 @@ public enum RunMode /// Executes the command on a different thread from the gateway one. /// Async -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Utilities/QuotationAliasUtils.cs b/src/Kook.Net.Commands/Utilities/QuotationAliasUtils.cs index 2dd32299..fefab2e8 100644 --- a/src/Kook.Net.Commands/Utilities/QuotationAliasUtils.cs +++ b/src/Kook.Net.Commands/Utilities/QuotationAliasUtils.cs @@ -91,4 +91,4 @@ internal static Dictionary GetDefaultAliasMap }; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Commands/Utilities/ReflectionUtils.cs b/src/Kook.Net.Commands/Utilities/ReflectionUtils.cs index f25871aa..1dadf144 100644 --- a/src/Kook.Net.Commands/Utilities/ReflectionUtils.cs +++ b/src/Kook.Net.Commands/Utilities/ReflectionUtils.cs @@ -24,7 +24,7 @@ internal static Func CreateBuilder(TypeInfo typeInfo, Co args[i] = GetMember(commands, services, parameters[i].ParameterType, typeInfo); var obj = InvokeConstructor(constructor, args, typeInfo); - foreach(var property in properties) + foreach (var property in properties) property.SetValue(obj, GetMember(commands, services, property.PropertyType, typeInfo)); return obj; }; @@ -75,4 +75,4 @@ private static object GetMember(CommandService commands, IServiceProvider servic return service; throw new InvalidOperationException($"Failed to create \"{ownerType.FullName}\", dependency \"{memberType.Name}\" was not found."); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/AssemblyInfo.cs b/src/Kook.Net.Core/AssemblyInfo.cs index f1e70360..839a22de 100644 --- a/src/Kook.Net.Core/AssemblyInfo.cs +++ b/src/Kook.Net.Core/AssemblyInfo.cs @@ -5,4 +5,4 @@ [assembly: InternalsVisibleTo("Kook.Net.WebSocket")] [assembly: InternalsVisibleTo("Kook.Net.Commands")] [assembly: InternalsVisibleTo("Kook.Net.Tests.Unit")] -[assembly: InternalsVisibleTo("Kook.Net.Tests.Integration")] \ No newline at end of file +[assembly: InternalsVisibleTo("Kook.Net.Tests.Integration")] diff --git a/src/Kook.Net.Core/Audio/AudioApplication.cs b/src/Kook.Net.Core/Audio/AudioApplication.cs index 4095894c..a8044e67 100644 --- a/src/Kook.Net.Core/Audio/AudioApplication.cs +++ b/src/Kook.Net.Core/Audio/AudioApplication.cs @@ -5,4 +5,4 @@ public enum AudioApplication : int Voice, Music, Mixed -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Audio/AudioInStream.cs b/src/Kook.Net.Core/Audio/AudioInStream.cs index 76dfbdc1..b20a3e00 100644 --- a/src/Kook.Net.Core/Audio/AudioInStream.cs +++ b/src/Kook.Net.Core/Audio/AudioInStream.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading; using System.Threading.Tasks; @@ -9,10 +9,10 @@ public abstract class AudioInStream : AudioStream public abstract int AvailableFrames { get; } public override bool CanRead => true; - public override bool CanWrite => true; + public override bool CanWrite => true; public abstract Task ReadFrameAsync(CancellationToken cancelToken); public abstract bool TryReadFrame(CancellationToken cancelToken, out RTPFrame frame); public override Task FlushAsync(CancellationToken cancelToken) { throw new NotSupportedException(); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Audio/AudioOutStream.cs b/src/Kook.Net.Core/Audio/AudioOutStream.cs index 98faa0a8..94219f3a 100644 --- a/src/Kook.Net.Core/Audio/AudioOutStream.cs +++ b/src/Kook.Net.Core/Audio/AudioOutStream.cs @@ -19,4 +19,4 @@ public override void SetLength(long value) => /// Seeking this stream is not supported.. public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Audio/AudioStream.cs b/src/Kook.Net.Core/Audio/AudioStream.cs index e6ed4528..3a02b094 100644 --- a/src/Kook.Net.Core/Audio/AudioStream.cs +++ b/src/Kook.Net.Core/Audio/AudioStream.cs @@ -12,7 +12,7 @@ public abstract class AudioStream : Stream public override bool CanWrite => false; /// This stream does not accept headers. - public virtual void WriteHeader(ushort seq, uint timestamp, bool missed) => + public virtual void WriteHeader(ushort seq, uint timestamp, bool missed) => throw new InvalidOperationException("This stream does not accept headers."); public override void Write(byte[] buffer, int offset, int count) { @@ -31,7 +31,7 @@ public void Clear() /// /// Reading stream length is not supported. - public override long Length => + public override long Length => throw new NotSupportedException(); /// @@ -54,4 +54,4 @@ public override void SetLength(long value) => /// Seeking this stream is not supported.. public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Audio/IAudioClient.cs b/src/Kook.Net.Core/Audio/IAudioClient.cs index e02c0c79..4e604fc5 100644 --- a/src/Kook.Net.Core/Audio/IAudioClient.cs +++ b/src/Kook.Net.Core/Audio/IAudioClient.cs @@ -35,4 +35,4 @@ public interface IAudioClient : IDisposable AudioOutStream CreatePCMStream(AudioApplication application, int? bitrate = null, int bufferMillis = 1000, int packetLoss = 30); /// Creates a new direct outgoing stream accepting PCM (raw) data. This is a direct stream with no internal timer. AudioOutStream CreateDirectPCMStream(AudioApplication application, int? bitrate = null, int packetLoss = 30); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Audio/RTPFrame.cs b/src/Kook.Net.Core/Audio/RTPFrame.cs index 7694a4a4..602e1665 100644 --- a/src/Kook.Net.Core/Audio/RTPFrame.cs +++ b/src/Kook.Net.Core/Audio/RTPFrame.cs @@ -14,4 +14,4 @@ public RTPFrame(ushort sequence, uint timestamp, byte[] payload, bool missed) Payload = payload; Missed = missed; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Commands/ICommandContext.cs b/src/Kook.Net.Core/Commands/ICommandContext.cs index 5359a9ee..63f08aad 100644 --- a/src/Kook.Net.Core/Commands/ICommandContext.cs +++ b/src/Kook.Net.Core/Commands/ICommandContext.cs @@ -25,4 +25,4 @@ public interface ICommandContext /// Gets the that the command is interpreted from. /// IUserMessage Message { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/ConnectionState.cs b/src/Kook.Net.Core/ConnectionState.cs index 381787a6..ed404f1b 100644 --- a/src/Kook.Net.Core/ConnectionState.cs +++ b/src/Kook.Net.Core/ConnectionState.cs @@ -11,4 +11,4 @@ public enum ConnectionState : byte Connected, /// The client is disconnecting from Kook. Disconnecting -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Activities/ActivityType.cs b/src/Kook.Net.Core/Entities/Activities/ActivityType.cs index 49593d81..98d7bc39 100644 --- a/src/Kook.Net.Core/Entities/Activities/ActivityType.cs +++ b/src/Kook.Net.Core/Entities/Activities/ActivityType.cs @@ -13,4 +13,4 @@ public enum ActivityType /// Specifies that the activity is music. /// Music = 2 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Activities/GameProperties.cs b/src/Kook.Net.Core/Entities/Activities/GameProperties.cs index e98f1d97..4a59c2fe 100644 --- a/src/Kook.Net.Core/Entities/Activities/GameProperties.cs +++ b/src/Kook.Net.Core/Entities/Activities/GameProperties.cs @@ -14,4 +14,4 @@ public class GameProperties /// Gets or sets the icon URL of the game. /// public string IconUrl { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Activities/GameType.cs b/src/Kook.Net.Core/Entities/Activities/GameType.cs index b08ac7f7..b6a9fddf 100644 --- a/src/Kook.Net.Core/Entities/Activities/GameType.cs +++ b/src/Kook.Net.Core/Entities/Activities/GameType.cs @@ -17,4 +17,4 @@ public enum GameType /// Specifies that the game is a process. /// Process = 2 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Activities/IActivity.cs b/src/Kook.Net.Core/Entities/Activities/IActivity.cs index 168f1451..f6f2848b 100644 --- a/src/Kook.Net.Core/Entities/Activities/IActivity.cs +++ b/src/Kook.Net.Core/Entities/Activities/IActivity.cs @@ -5,5 +5,5 @@ namespace Kook; /// public interface IActivity { - -} \ No newline at end of file + +} diff --git a/src/Kook.Net.Core/Entities/Activities/IGame.cs b/src/Kook.Net.Core/Entities/Activities/IGame.cs index 06519245..a2594017 100644 --- a/src/Kook.Net.Core/Entities/Activities/IGame.cs +++ b/src/Kook.Net.Core/Entities/Activities/IGame.cs @@ -68,4 +68,4 @@ public interface IGame : IActivity, IEntity, IDeletable /// A task that represents the asynchronous modification operation. /// Task ModifyAsync(Action func, RequestOptions options = null); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Activities/Music.cs b/src/Kook.Net.Core/Entities/Activities/Music.cs index ae32ac41..afe986a5 100644 --- a/src/Kook.Net.Core/Entities/Activities/Music.cs +++ b/src/Kook.Net.Core/Entities/Activities/Music.cs @@ -5,4 +5,4 @@ public class Music public MusicProvider Provider { get; set; } public string Name { get; set; } public string Singer { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Activities/MusicProvider.cs b/src/Kook.Net.Core/Entities/Activities/MusicProvider.cs index a679a4e1..f7b43e46 100644 --- a/src/Kook.Net.Core/Entities/Activities/MusicProvider.cs +++ b/src/Kook.Net.Core/Entities/Activities/MusicProvider.cs @@ -21,4 +21,4 @@ public enum MusicProvider /// Specifies that the music provider is KuGou. /// KuGouMusic = 3 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Badges/BadgeStyle.cs b/src/Kook.Net.Core/Entities/Badges/BadgeStyle.cs index 552294dc..c9649543 100644 --- a/src/Kook.Net.Core/Entities/Badges/BadgeStyle.cs +++ b/src/Kook.Net.Core/Entities/Badges/BadgeStyle.cs @@ -17,4 +17,4 @@ public enum BadgeStyle /// The badge contains the number of both online and all members in the guild. /// OnlineAndTotalMemberCount = 2 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/CacheMode.cs b/src/Kook.Net.Core/Entities/CacheMode.cs index 09a94d52..d438152c 100644 --- a/src/Kook.Net.Core/Entities/CacheMode.cs +++ b/src/Kook.Net.Core/Entities/CacheMode.cs @@ -13,4 +13,4 @@ public enum CacheMode /// Only allows the object to be pulled from the existing cache. /// CacheOnly -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/ChannelType.cs b/src/Kook.Net.Core/Entities/Channels/ChannelType.cs index 7b6e26b7..dbac7bac 100644 --- a/src/Kook.Net.Core/Entities/Channels/ChannelType.cs +++ b/src/Kook.Net.Core/Entities/Channels/ChannelType.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Specifies the type of a guild channel. @@ -9,24 +9,24 @@ public enum ChannelType /// Specifies that the type of the channel is unknown. /// Unspecified = -1, - + /// /// Specifies that the channel is a guild category channel. /// Category = 0, - + /// /// Specifies that the channel is a guild text channel. /// Text = 1, - + /// /// Specifies that the channel is a guild voice channel. /// Voice = 2, - + /// /// Specifies that the channel is a direct message channel. /// DM = 3 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/CreateCategoryChannelProperties.cs b/src/Kook.Net.Core/Entities/Channels/CreateCategoryChannelProperties.cs index d864f667..00236e28 100644 --- a/src/Kook.Net.Core/Entities/Channels/CreateCategoryChannelProperties.cs +++ b/src/Kook.Net.Core/Entities/Channels/CreateCategoryChannelProperties.cs @@ -7,4 +7,4 @@ namespace Kook; public class CreateCategoryChannelProperties : CreateGuildChannelProperties { -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/CreateGuildChannelProperties.cs b/src/Kook.Net.Core/Entities/Channels/CreateGuildChannelProperties.cs index 7117890a..a983f115 100644 --- a/src/Kook.Net.Core/Entities/Channels/CreateGuildChannelProperties.cs +++ b/src/Kook.Net.Core/Entities/Channels/CreateGuildChannelProperties.cs @@ -6,4 +6,4 @@ namespace Kook; public class CreateGuildChannelProperties { -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/CreateTextChannelProperties.cs b/src/Kook.Net.Core/Entities/Channels/CreateTextChannelProperties.cs index 0684f2e1..3be4a86c 100644 --- a/src/Kook.Net.Core/Entities/Channels/CreateTextChannelProperties.cs +++ b/src/Kook.Net.Core/Entities/Channels/CreateTextChannelProperties.cs @@ -14,7 +14,7 @@ public class CreateTextChannelProperties : CreateGuildChannelProperties /// channel topic or description to the desired value. /// public string Topic { get; set; } - + /// /// Gets or sets the category ID for this channel. /// @@ -24,4 +24,4 @@ public class CreateTextChannelProperties : CreateGuildChannelProperties /// from any parents. /// public ulong? CategoryId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/CreateVoiceChannelProperties.cs b/src/Kook.Net.Core/Entities/Channels/CreateVoiceChannelProperties.cs index 04aa78af..48f925a7 100644 --- a/src/Kook.Net.Core/Entities/Channels/CreateVoiceChannelProperties.cs +++ b/src/Kook.Net.Core/Entities/Channels/CreateVoiceChannelProperties.cs @@ -10,12 +10,12 @@ public class CreateVoiceChannelProperties : CreateGuildChannelProperties /// Gets or sets the voice quality that the clients in this voice channel are requested to use. /// public VoiceQuality? VoiceQuality { get; set; } - + /// /// Gets or sets the maximum number of users that can be present in a channel, or null if none. /// public int? UserLimit { get; set; } - + /// /// Gets or sets the category ID for this channel. /// @@ -25,4 +25,4 @@ public class CreateVoiceChannelProperties : CreateGuildChannelProperties /// from any parents. /// public ulong? CategoryId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/Direction.cs b/src/Kook.Net.Core/Entities/Channels/Direction.cs index b1f82d5c..434b2406 100644 --- a/src/Kook.Net.Core/Entities/Channels/Direction.cs +++ b/src/Kook.Net.Core/Entities/Channels/Direction.cs @@ -27,4 +27,4 @@ public enum Direction /// The message(s) should be retrieved after a message. /// After -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/IAudioChannel.cs b/src/Kook.Net.Core/Entities/Channels/IAudioChannel.cs index a945134a..42b74ab2 100644 --- a/src/Kook.Net.Core/Entities/Channels/IAudioChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/IAudioChannel.cs @@ -1,9 +1,9 @@ -namespace Kook; +namespace Kook; /// /// Represents a generic audio channel. /// public interface IAudioChannel : IChannel { - -} \ No newline at end of file + +} diff --git a/src/Kook.Net.Core/Entities/Channels/ICategoryChannel.cs b/src/Kook.Net.Core/Entities/Channels/ICategoryChannel.cs index 5f8f6af2..f91ab761 100644 --- a/src/Kook.Net.Core/Entities/Channels/ICategoryChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/ICategoryChannel.cs @@ -1,9 +1,9 @@ -namespace Kook; +namespace Kook; /// /// Represents a generic category channel. /// public interface ICategoryChannel : IGuildChannel { - -} \ No newline at end of file + +} diff --git a/src/Kook.Net.Core/Entities/Channels/IChannel.cs b/src/Kook.Net.Core/Entities/Channels/IChannel.cs index 22d3d40c..09058adc 100644 --- a/src/Kook.Net.Core/Entities/Channels/IChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/IChannel.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Represents a generic channel. @@ -18,7 +18,7 @@ public interface IChannel : IEntity #endregion #region Users - + /// /// Gets a collection of users that are able to view the channel or are currently in this channel. /// @@ -40,7 +40,7 @@ public interface IChannel : IEntity /// Paged collection of users. /// IAsyncEnumerable> GetUsersAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); - + /// /// Gets a user in this channel. /// @@ -54,4 +54,4 @@ public interface IChannel : IEntity Task GetUserAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/IDMChannel.cs b/src/Kook.Net.Core/Entities/Channels/IDMChannel.cs index 00c916bd..f88116a4 100644 --- a/src/Kook.Net.Core/Entities/Channels/IDMChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/IDMChannel.cs @@ -24,7 +24,7 @@ public interface IDMChannel : IMessageChannel, IPrivateChannel, IEntity /// A that represents the chat code of the direct-message channel. /// Guid ChatCode { get; } - + /// /// Gets the recipient of all messages in this channel. /// @@ -32,7 +32,7 @@ public interface IDMChannel : IMessageChannel, IPrivateChannel, IEntity /// A user object that represents the other user in this channel. /// IUser Recipient { get; } - + /// /// Closes this private channel, removing it from your channel list. /// @@ -43,7 +43,7 @@ public interface IDMChannel : IMessageChannel, IPrivateChannel, IEntity Task CloseAsync(RequestOptions options = null); #endregion - + #region Send Messages /// @@ -103,4 +103,4 @@ Task> SendCardsAsync(IEnumerable cards, IQuote quote = null, RequestOptions options = null); #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/IGuildChannel.cs b/src/Kook.Net.Core/Entities/Channels/IGuildChannel.cs index 9aa273df..7efd28f7 100644 --- a/src/Kook.Net.Core/Entities/Channels/IGuildChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/IGuildChannel.cs @@ -6,7 +6,7 @@ namespace Kook; public interface IGuildChannel : IChannel, IDeletable { #region General - + /// /// Gets the guild associated with this channel. /// @@ -14,7 +14,7 @@ public interface IGuildChannel : IChannel, IDeletable /// A guild object that this channel belongs to. /// IGuild Guild { get; } - + /// /// Gets the guild ID associated with this channel. /// @@ -40,7 +40,7 @@ public interface IGuildChannel : IChannel, IDeletable /// A representing the type of this channel. /// ChannelType Type { get; } - + /// /// Gets the identifier of the user who created this channel. /// @@ -48,7 +48,7 @@ public interface IGuildChannel : IChannel, IDeletable /// A representing the identifier of the user who created this channel. /// ulong CreatorId { get; } - + /// /// Gets a collection of permission overwrites for roles for this channel. /// @@ -56,7 +56,7 @@ public interface IGuildChannel : IChannel, IDeletable /// A collection of overwrites for roles associated with this channel. /// IReadOnlyCollection RolePermissionOverwrites { get; } - + /// /// Gets a collection of permission overwrites for users for this channel. /// @@ -110,7 +110,7 @@ public interface IGuildChannel : IChannel, IDeletable /// An overwrite object for the targeted user; null if none is set. /// OverwritePermissions? GetPermissionOverwrite(IUser user); - + /// /// Removes the permission overwrite for the given role, if one exists. /// @@ -174,7 +174,7 @@ public interface IGuildChannel : IChannel, IDeletable /// A task representing the asynchronous permission operation for adding the specified permissions to the channel. /// Task ModifyPermissionOverwriteAsync(IGuildUser user, Func func, RequestOptions options = null); - + #endregion #region Users @@ -192,7 +192,7 @@ public interface IGuildChannel : IChannel, IDeletable /// Paged collection of users. /// new IAsyncEnumerable> GetUsersAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); - + /// /// Gets a user in this channel. /// @@ -206,4 +206,4 @@ public interface IGuildChannel : IChannel, IDeletable new Task GetUserAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/IMessageChannel.cs b/src/Kook.Net.Core/Entities/Channels/IMessageChannel.cs index 0c241da7..b234ff63 100644 --- a/src/Kook.Net.Core/Entities/Channels/IMessageChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/IMessageChannel.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; public interface IMessageChannel : IChannel { @@ -20,8 +20,8 @@ public interface IMessageChannel : IChannel /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the identifier and timestamp of the sent message. /// - Task> SendFileAsync(string path, string fileName = null, - AttachmentType type = AttachmentType.File, IQuote quote = null, IUser ephemeralUser = null, + Task> SendFileAsync(string path, string fileName = null, + AttachmentType type = AttachmentType.File, IQuote quote = null, IUser ephemeralUser = null, RequestOptions options = null); /// @@ -40,8 +40,8 @@ Task> SendFileAsync(string path, string fileName = /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the identifier and timestamp of the sent message. /// - Task> SendFileAsync(Stream stream, string fileName, - AttachmentType type = AttachmentType.File, IQuote quote = null, IUser ephemeralUser = null, + Task> SendFileAsync(Stream stream, string fileName, + AttachmentType type = AttachmentType.File, IQuote quote = null, IUser ephemeralUser = null, RequestOptions options = null); /// /// Sends a file to this message channel. @@ -98,7 +98,7 @@ Task> SendCardAsync(ICard card, /// Task> SendCardsAsync(IEnumerable cards, IQuote quote = null, IUser ephemeralUser = null, RequestOptions options = null); - + /// /// Gets a message from this message channel. /// @@ -112,9 +112,9 @@ Task> SendCardsAsync(IEnumerable cards, Task GetMessageAsync(Guid id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); #endregion - + #region Get Messages - + /// /// Gets the last N messages from this message channel. /// @@ -142,7 +142,7 @@ Task> SendCardsAsync(IEnumerable cards, /// /// Paged collection of messages. /// - IAsyncEnumerable> GetMessagesAsync(int limit = KookConfig.MaxMessagesPerBatch, + IAsyncEnumerable> GetMessagesAsync(int limit = KookConfig.MaxMessagesPerBatch, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); /// /// Gets a collection of messages in this channel. @@ -174,7 +174,7 @@ IAsyncEnumerable> GetMessagesAsync(int limit = Koo /// /// Paged collection of messages. /// - IAsyncEnumerable> GetMessagesAsync(Guid referenceMessageId, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, + IAsyncEnumerable> GetMessagesAsync(Guid referenceMessageId, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); /// /// Gets a collection of messages in this channel. @@ -206,11 +206,11 @@ IAsyncEnumerable> GetMessagesAsync(Guid referenceM /// /// Paged collection of messages. /// - IAsyncEnumerable> GetMessagesAsync(IMessage referenceMessage, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, + IAsyncEnumerable> GetMessagesAsync(IMessage referenceMessage, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); #endregion - + #region Delete Messages /// @@ -231,7 +231,7 @@ IAsyncEnumerable> GetMessagesAsync(IMessage refere Task DeleteMessageAsync(IMessage message, RequestOptions options = null); #endregion - + #region Modify Messages /// @@ -250,4 +250,4 @@ IAsyncEnumerable> GetMessagesAsync(IMessage refere Task ModifyMessageAsync(Guid messageId, Action func, RequestOptions options = null); #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/INestedChannel.cs b/src/Kook.Net.Core/Entities/Channels/INestedChannel.cs index 2ea9b53b..4436bfb7 100644 --- a/src/Kook.Net.Core/Entities/Channels/INestedChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/INestedChannel.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Represents a type of guild channel that can be nested within a category. @@ -15,7 +15,7 @@ public interface INestedChannel : IGuildChannel /// null if none is set. /// ulong? CategoryId { get; } - + /// /// Specifies whether the permissions of this channel is synchronized with its parent channel. /// @@ -23,7 +23,7 @@ public interface INestedChannel : IGuildChannel /// A indicating whether the permissions of this channel is synchronized with its parent channel. /// bool? IsPermissionSynced { get; } - + /// /// Gets the parent (category) channel of this channel. /// @@ -60,7 +60,7 @@ public interface INestedChannel : IGuildChannel /// metadata object containing information for the created invite. /// Task CreateInviteAsync(InviteMaxAge maxAge = InviteMaxAge._604800, InviteMaxUses maxUses = InviteMaxUses.Unlimited, RequestOptions options = null); - + /// /// Creates a new invite to this channel. /// @@ -72,6 +72,6 @@ public interface INestedChannel : IGuildChannel /// metadata object containing information for the created invite. /// Task CreateInviteAsync(int? maxAge = 604800, int? maxUses = null, RequestOptions options = null); - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/IPrivateChannel.cs b/src/Kook.Net.Core/Entities/Channels/IPrivateChannel.cs index ea676310..468f0269 100644 --- a/src/Kook.Net.Core/Entities/Channels/IPrivateChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/IPrivateChannel.cs @@ -14,4 +14,4 @@ public interface IPrivateChannel : IChannel /// A read-only collection of users that can access this channel. /// IReadOnlyCollection Recipients { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/ITextChannel.cs b/src/Kook.Net.Core/Entities/Channels/ITextChannel.cs index 35c7990e..34e5a61b 100644 --- a/src/Kook.Net.Core/Entities/Channels/ITextChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/ITextChannel.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Represents a generic channel in a guild that can send and receive messages. @@ -14,7 +14,7 @@ public interface ITextChannel : INestedChannel, IMentionable, IMessageChannel /// A string representing the topic set in the channel; null if none is set. /// string Topic { get; } - + /// /// Gets the current slow-mode delay for this channel. /// @@ -33,9 +33,9 @@ public interface ITextChannel : INestedChannel, IMentionable, IMessageChannel /// /// Task ModifyAsync(Action func, RequestOptions options = null); - + #endregion - + /// /// Gets a collection of pinned messages in this channel. /// @@ -45,4 +45,4 @@ public interface ITextChannel : INestedChannel, IMentionable, IMessageChannel /// The task result contains a collection of messages found in the pinned messages. /// Task> GetPinnedMessagesAsync(RequestOptions options = null); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/IVoiceChannel.cs b/src/Kook.Net.Core/Entities/Channels/IVoiceChannel.cs index 18d510ab..9fb0887a 100644 --- a/src/Kook.Net.Core/Entities/Channels/IVoiceChannel.cs +++ b/src/Kook.Net.Core/Entities/Channels/IVoiceChannel.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Represents a generic voice channel in a guild. @@ -13,7 +13,7 @@ public interface IVoiceChannel : INestedChannel, IAudioChannel, IMentionable /// client(s) to use. /// VoiceQuality? VoiceQuality { get; } - + /// /// Gets the max number of users allowed to be connected to this channel at once. /// @@ -30,7 +30,7 @@ public interface IVoiceChannel : INestedChannel, IAudioChannel, IMentionable /// A string representing the url that clients should connect to to join this voice channel. /// string ServerUrl { get; } - + /// /// Gets whether this voice channel is locked by a password. /// @@ -38,7 +38,7 @@ public interface IVoiceChannel : INestedChannel, IAudioChannel, IMentionable /// A bool representing whether this voice channel is locked by a password. /// bool HasPassword { get; } - + /// /// Modifies this voice channel. /// @@ -60,4 +60,4 @@ public interface IVoiceChannel : INestedChannel, IAudioChannel, IMentionable /// s that are connected to this voice channel. /// Task> GetConnectedUsersAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/MessageSource.cs b/src/Kook.Net.Core/Entities/Channels/MessageSource.cs index 447c80e6..a210058c 100644 --- a/src/Kook.Net.Core/Entities/Channels/MessageSource.cs +++ b/src/Kook.Net.Core/Entities/Channels/MessageSource.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Specifies the source of the Kook message. @@ -17,4 +17,4 @@ public enum MessageSource /// The message is sent by a bot. /// Bot -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/ModifyGuildChannelProperties.cs b/src/Kook.Net.Core/Entities/Channels/ModifyGuildChannelProperties.cs index 25b55242..7c4dfef4 100644 --- a/src/Kook.Net.Core/Entities/Channels/ModifyGuildChannelProperties.cs +++ b/src/Kook.Net.Core/Entities/Channels/ModifyGuildChannelProperties.cs @@ -30,4 +30,4 @@ public class ModifyGuildChannelProperties /// is set; if this is null, the parent of this channel will not be modified. /// public ulong? CategoryId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/ModifyTextChannelProperties.cs b/src/Kook.Net.Core/Entities/Channels/ModifyTextChannelProperties.cs index b0a0d53e..c2c4b34d 100644 --- a/src/Kook.Net.Core/Entities/Channels/ModifyTextChannelProperties.cs +++ b/src/Kook.Net.Core/Entities/Channels/ModifyTextChannelProperties.cs @@ -27,4 +27,4 @@ public class ModifyTextChannelProperties : ModifyGuildChannelProperties /// /// public SlowModeInterval? SlowModeInterval { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/ModifyVoiceChannelProperties.cs b/src/Kook.Net.Core/Entities/Channels/ModifyVoiceChannelProperties.cs index 58526ded..80b41c01 100644 --- a/src/Kook.Net.Core/Entities/Channels/ModifyVoiceChannelProperties.cs +++ b/src/Kook.Net.Core/Entities/Channels/ModifyVoiceChannelProperties.cs @@ -30,4 +30,4 @@ public class ModifyVoiceChannelProperties : ModifyGuildChannelProperties /// Gets or sets the password of the channel, or empty string to clear the password; null if not set. /// public string Password { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/SlowModeInterval.cs b/src/Kook.Net.Core/Entities/Channels/SlowModeInterval.cs index 3517d8c1..42435a73 100644 --- a/src/Kook.Net.Core/Entities/Channels/SlowModeInterval.cs +++ b/src/Kook.Net.Core/Entities/Channels/SlowModeInterval.cs @@ -61,4 +61,4 @@ public enum SlowModeInterval /// Each user needs to wait for 6 hours (21600 seconds) before sending another message. /// _21600 = 21600 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Channels/VoiceQuality.cs b/src/Kook.Net.Core/Entities/Channels/VoiceQuality.cs index 91eb9a69..ad84eeb6 100644 --- a/src/Kook.Net.Core/Entities/Channels/VoiceQuality.cs +++ b/src/Kook.Net.Core/Entities/Channels/VoiceQuality.cs @@ -45,4 +45,4 @@ public enum VoiceQuality /// This quality needs the boost level to reach LV5. /// _320kbps = 7, -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Emotes/Emoji.cs b/src/Kook.Net.Core/Entities/Emotes/Emoji.cs index 92fc666a..0a13514e 100644 --- a/src/Kook.Net.Core/Entities/Emotes/Emoji.cs +++ b/src/Kook.Net.Core/Entities/Emotes/Emoji.cs @@ -87,9 +87,11 @@ public static Emoji Parse(string emojiStr) internal bool TryParseAsUnicodePoint(string unicodePoint, out string name) { name = null; - if (!unicodePoint.StartsWith("[#") || !unicodePoint.EndsWith(";]")) return false; + if (!unicodePoint.StartsWith("[#") || !unicodePoint.EndsWith(";]")) + return false; #if NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER - if (!int.TryParse(unicodePoint[2..^2], out int codePoint)) return false; + if (!int.TryParse(unicodePoint[2..^2], out int codePoint)) + return false; #else if (!int.TryParse(unicodePoint.Substring(2, unicodePoint.Length - 4), out int codePoint)) return false; #endif @@ -1847,4 +1849,4 @@ private static IReadOnlyDictionary> UnicodesA } public static implicit operator Emoji(string s) => Parse(s); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Emotes/EmojiType.cs b/src/Kook.Net.Core/Entities/Emotes/EmojiType.cs index 0db79c53..e2905a5d 100644 --- a/src/Kook.Net.Core/Entities/Emotes/EmojiType.cs +++ b/src/Kook.Net.Core/Entities/Emotes/EmojiType.cs @@ -13,4 +13,4 @@ public enum EmojiType /// The emoji is animated. /// Animated = 2 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Emotes/Emote.cs b/src/Kook.Net.Core/Entities/Emotes/Emote.cs index b631dd81..15d22bbe 100644 --- a/src/Kook.Net.Core/Entities/Emotes/Emote.cs +++ b/src/Kook.Net.Core/Entities/Emotes/Emote.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; using System.Globalization; using System.Text.RegularExpressions; @@ -7,40 +7,42 @@ namespace Kook; [DebuggerDisplay("{DebuggerDisplay,nq}")] public class Emote : IEmote { - + internal static readonly Regex PlainTextEmojiRegex = new Regex(@"\[:(?[^:]{1,32}?):(?\d{1,20}\/\w{1,20})\]", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline); - + internal static readonly Regex KMarkdownEmojiRegex = new Regex(@"(\(emj\))(?[^\(\)]{1,32}?)\1\[(?\d{1,20}\/\w{1,20})\]", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline); - + public string Id { get; } - + public string Name { get; } - + public bool? Animated { get; } - + internal Emote(string id, string name, bool? animated = null) { Id = id; Name = name; Animated = animated; } - + public override bool Equals(object other) { - if (other == null) return false; - if (other == this) return true; + if (other == null) + return false; + if (other == this) + return true; - if (other is not Emote otherEmote) + if (other is not Emote otherEmote) return false; return Id == otherEmote.Id; } - + public override int GetHashCode() => Id.GetHashCode(); - + /// Parses an from its raw format. /// /// The raw encoding of an emote; for example, @@ -56,7 +58,7 @@ public static Emote Parse(string text, TagMode tagMode) return result; throw new ArgumentException(message: "Invalid emote format.", paramName: nameof(text)); } - + /// Tries to parse an from its raw format. /// /// The raw encoding of an emote; for example, @@ -87,7 +89,7 @@ public static bool TryParse(string text, out Emote result, TagMode tagMode) return false; } - + /// /// Gets a string representation of the emote in KMarkdown format. /// @@ -96,6 +98,6 @@ public static bool TryParse(string text, out Emote result, TagMode tagMode) /// Gets a string representation of the emote in plain text format. /// public string ToPlainTextString() => $"[:{Name}:{Id}]"; - + private string DebuggerDisplay => $"{Name} ({Id})"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Emotes/GuildEmote.cs b/src/Kook.Net.Core/Entities/Emotes/GuildEmote.cs index f4c0cf94..472d5bea 100644 --- a/src/Kook.Net.Core/Entities/Emotes/GuildEmote.cs +++ b/src/Kook.Net.Core/Entities/Emotes/GuildEmote.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; using System.Globalization; namespace Kook; @@ -9,7 +9,7 @@ namespace Kook; [DebuggerDisplay(@"{DebuggerDisplay,nq}")] public class GuildEmote : Emote { - internal GuildEmote(string id, string name, bool? animated, ulong guildId, ulong? creatorId) + internal GuildEmote(string id, string name, bool? animated, ulong guildId, ulong? creatorId) : base(id, name, animated) { GuildId = guildId; @@ -23,7 +23,7 @@ internal GuildEmote(string id, string name, bool? animated, ulong guildId, ulong /// A ulong that identifies the guild this emote is attached to. /// public ulong GuildId { get; } - + /// /// Gets the user who created this emote. /// @@ -32,7 +32,7 @@ internal GuildEmote(string id, string name, bool? animated, ulong guildId, ulong /// null if unknown. /// public ulong? CreatorId { get; } - + private string DebuggerDisplay => $"{Name} ({Id}{(Animated == true ? ", Animated" : "")})"; /// /// Gets the raw representation of the emote. @@ -42,4 +42,4 @@ internal GuildEmote(string id, string name, bool? animated, ulong guildId, ulong /// public override string ToString() => $"(emj){Name}(emj)[{Id}]"; internal GuildEmote Clone() => MemberwiseClone() as GuildEmote; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Emotes/IEmote.cs b/src/Kook.Net.Core/Entities/Emotes/IEmote.cs index 10464456..1cbd1d3a 100644 --- a/src/Kook.Net.Core/Entities/Emotes/IEmote.cs +++ b/src/Kook.Net.Core/Entities/Emotes/IEmote.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Represents a general container for any type of emote in a message. @@ -12,4 +12,4 @@ public interface IEmote : IEntity /// A string representing the display name or the Unicode representation (e.g. 🤔) of this emote. /// string Name { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Guilds/BoostLevel.cs b/src/Kook.Net.Core/Entities/Guilds/BoostLevel.cs index bcb3af98..186bebca 100644 --- a/src/Kook.Net.Core/Entities/Guilds/BoostLevel.cs +++ b/src/Kook.Net.Core/Entities/Guilds/BoostLevel.cs @@ -33,4 +33,4 @@ public enum BoostLevel /// Boost level 6. /// Level6 = 6, -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Guilds/IBan.cs b/src/Kook.Net.Core/Entities/Guilds/IBan.cs index b286fdd0..bcccb57c 100644 --- a/src/Kook.Net.Core/Entities/Guilds/IBan.cs +++ b/src/Kook.Net.Core/Entities/Guilds/IBan.cs @@ -26,4 +26,4 @@ public interface IBan /// A string containing the reason behind the ban; null if none is specified. /// string Reason { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Guilds/IGuild.cs b/src/Kook.Net.Core/Entities/Guilds/IGuild.cs index 95ae92ae..eb2166a0 100644 --- a/src/Kook.Net.Core/Entities/Guilds/IGuild.cs +++ b/src/Kook.Net.Core/Entities/Guilds/IGuild.cs @@ -1,4 +1,4 @@ -using System.Collections.Immutable; +using System.Collections.Immutable; namespace Kook; @@ -155,7 +155,7 @@ public interface IGuild : IEntity /// if the guild does not have a recommendation. /// IRecommendInfo RecommendInfo { get; } - + #endregion #region Guilds @@ -274,9 +274,9 @@ public interface IGuild : IEntity Task RemoveBanAsync(ulong userId, RequestOptions options = null); #endregion - + #region Channels - + /// /// Gets a collection of all channels in this guild. /// @@ -352,7 +352,7 @@ public interface IGuild : IEntity /// Task> GetCategoryChannelsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); - + /// /// Gets the default text channel for this guild. /// @@ -373,7 +373,7 @@ Task> GetCategoryChannelsAsync(CacheMode m /// if none is found. /// Task GetWelcomeChannelAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); - + /// /// Creates a new text channel in this guild. /// @@ -407,7 +407,7 @@ Task> GetCategoryChannelsAsync(CacheMode m /// category channel. /// Task CreateCategoryChannelAsync(string name, Action func = null, RequestOptions options = null); - + #endregion #region Invites @@ -421,7 +421,7 @@ Task> GetCategoryChannelsAsync(CacheMode m /// invite, each representing information for an invite found within this guild. /// Task> GetInvitesAsync(RequestOptions options = null); - + /// /// Creates a new invite to this channel. /// @@ -433,7 +433,7 @@ Task> GetCategoryChannelsAsync(CacheMode m /// metadata object containing information for the created invite. /// Task CreateInviteAsync(InviteMaxAge maxAge = InviteMaxAge._604800, InviteMaxUses maxUses = InviteMaxUses.Unlimited, RequestOptions options = null); - + /// /// Creates a new invite to this channel. /// @@ -467,11 +467,11 @@ Task> GetCategoryChannelsAsync(CacheMode m /// A task that represents the asynchronous creation operation. The task result contains the newly created role. /// Task CreateRoleAsync(string name, RequestOptions options = null); - + #endregion #region Users - + /// /// Gets a collection of all users in this guild. /// @@ -572,7 +572,7 @@ Task> GetCategoryChannelsAsync(CacheMode m /// users that matches the properties with the provided at . /// IAsyncEnumerable> SearchUsersAsync(Action func, int limit = KookConfig.MaxUsersPerBatch, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); - + #endregion #region Emotes @@ -658,4 +658,4 @@ Task> GetCategoryChannelsAsync(CacheMode m Task GetBadgeAsync(BadgeStyle style = BadgeStyle.GuildName, RequestOptions options = null); #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Guilds/IRecommendInfo.cs b/src/Kook.Net.Core/Entities/Guilds/IRecommendInfo.cs index 5ca22799..43d288e6 100644 --- a/src/Kook.Net.Core/Entities/Guilds/IRecommendInfo.cs +++ b/src/Kook.Net.Core/Entities/Guilds/IRecommendInfo.cs @@ -102,4 +102,4 @@ public interface IRecommendInfo /// An representing the number of days need to be waited before the recommendation information can be modified again. /// int DaysBeforeModify { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Guilds/NotifyType.cs b/src/Kook.Net.Core/Entities/Guilds/NotifyType.cs index 0c0965e0..76e77800 100644 --- a/src/Kook.Net.Core/Entities/Guilds/NotifyType.cs +++ b/src/Kook.Net.Core/Entities/Guilds/NotifyType.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Specifies that how the guild should notify the user. @@ -9,19 +9,19 @@ public enum NotifyType /// Notifies the user as the default behavior of the guild. /// Default = 0, - + /// /// Notifies the user of all messages. /// AcceptAll = 1, - + /// /// Notifies the user of the messages which mention the user. /// OnlyMentioned = 2, - + /// /// ]Never notifies the user. /// Muted = 3 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Guilds/RoleType.cs b/src/Kook.Net.Core/Entities/Guilds/RoleType.cs index b64a23ee..3910097d 100644 --- a/src/Kook.Net.Core/Entities/Guilds/RoleType.cs +++ b/src/Kook.Net.Core/Entities/Guilds/RoleType.cs @@ -21,4 +21,4 @@ public enum RoleType : ushort /// Represents tht role is the default everyone role. /// Everyone = 255 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/IDeletable.cs b/src/Kook.Net.Core/Entities/IDeletable.cs index 157a8347..5caddd73 100644 --- a/src/Kook.Net.Core/Entities/IDeletable.cs +++ b/src/Kook.Net.Core/Entities/IDeletable.cs @@ -10,4 +10,4 @@ public interface IDeletable /// /// The options to be used when sending the request. Task DeleteAsync(RequestOptions options = null); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/IEntity.cs b/src/Kook.Net.Core/Entities/IEntity.cs index 79f8800b..38358204 100644 --- a/src/Kook.Net.Core/Entities/IEntity.cs +++ b/src/Kook.Net.Core/Entities/IEntity.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; public interface IEntity where TId : IEquatable @@ -6,5 +6,5 @@ public interface IEntity /// /// Gets the unique identifier for this object. /// - TId Id { get; } -} \ No newline at end of file + TId Id { get; } +} diff --git a/src/Kook.Net.Core/Entities/IMentionable.cs b/src/Kook.Net.Core/Entities/IMentionable.cs index 8cb86c43..dc05da11 100644 --- a/src/Kook.Net.Core/Entities/IMentionable.cs +++ b/src/Kook.Net.Core/Entities/IMentionable.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Determines whether the object is mentionable or not. @@ -19,4 +19,4 @@ public interface IMentionable /// A string that is recognized by Kook as a mention in KMarkdown formatted text. /// string KMarkdownMention { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/IUpdateable.cs b/src/Kook.Net.Core/Entities/IUpdateable.cs index f41620e3..76c72508 100644 --- a/src/Kook.Net.Core/Entities/IUpdateable.cs +++ b/src/Kook.Net.Core/Entities/IUpdateable.cs @@ -19,4 +19,4 @@ public interface IUpdateable /// /// Task UpdateAsync(RequestOptions options = null); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Image.cs b/src/Kook.Net.Core/Entities/Image.cs index 53bb1fb2..b693071b 100644 --- a/src/Kook.Net.Core/Entities/Image.cs +++ b/src/Kook.Net.Core/Entities/Image.cs @@ -77,8 +77,9 @@ public Image(string path) /// public void Dispose() { - if (_isDisposed) return; + if (_isDisposed) + return; Stream?.Dispose(); _isDisposed = true; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Intimacies/IIntimacy.cs b/src/Kook.Net.Core/Entities/Intimacies/IIntimacy.cs index e79d1d41..acc707f1 100644 --- a/src/Kook.Net.Core/Entities/Intimacies/IIntimacy.cs +++ b/src/Kook.Net.Core/Entities/Intimacies/IIntimacy.cs @@ -28,7 +28,7 @@ public interface IIntimacy : IEntity /// A time at which the user read the message. /// DateTimeOffset LastReadAt { get; } - + /// /// Gets the time at which this intimacy was modified last time. /// @@ -44,7 +44,7 @@ public interface IIntimacy : IEntity /// A representing the score associated with this intimacy. /// int Score { get; } - + /// /// Gets the images associated with this intimacy. /// @@ -60,4 +60,4 @@ public interface IIntimacy : IEntity /// The options to be used when sending the request. /// A task that represents the asynchronous operation for updating the intimacy information. Task UpdateAsync(Action func, RequestOptions options); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Intimacies/IntimacyImage.cs b/src/Kook.Net.Core/Entities/Intimacies/IntimacyImage.cs index fe06f977..63d35058 100644 --- a/src/Kook.Net.Core/Entities/Intimacies/IntimacyImage.cs +++ b/src/Kook.Net.Core/Entities/Intimacies/IntimacyImage.cs @@ -31,4 +31,4 @@ internal IntimacyImage(uint id, string url) /// A representing the URL of the image of an intimacy. /// public string Url { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Intimacies/IntimacyProperties.cs b/src/Kook.Net.Core/Entities/Intimacies/IntimacyProperties.cs index 8bc30e04..6c2db164 100644 --- a/src/Kook.Net.Core/Entities/Intimacies/IntimacyProperties.cs +++ b/src/Kook.Net.Core/Entities/Intimacies/IntimacyProperties.cs @@ -20,4 +20,4 @@ public class IntimacyProperties /// The score to be set on the . /// public int Score { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Invites/IInvite.cs b/src/Kook.Net.Core/Entities/Invites/IInvite.cs index 7356e18b..497cf471 100644 --- a/src/Kook.Net.Core/Entities/Invites/IInvite.cs +++ b/src/Kook.Net.Core/Entities/Invites/IInvite.cs @@ -19,7 +19,7 @@ public interface IInvite : IEntity, IDeletable /// A string containing the full invite URL (e.g. https://kaihei.co/wEAF5t). /// string Url { get; } - + /// /// Gets the user that created this invite. /// @@ -74,7 +74,7 @@ public interface IInvite : IEntity, IDeletable /// A string containing the name of the guild that the invite points to. /// string GuildName { get; } - + /// /// Gets the time at which this invite will expire. /// @@ -113,4 +113,4 @@ public interface IInvite : IEntity, IDeletable /// An int representing the number of times this invite still remains; null if none is set. /// int? RemainingUses { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Invites/InviteMaxAge.cs b/src/Kook.Net.Core/Entities/Invites/InviteMaxAge.cs index 9cc8a252..e974aa65 100644 --- a/src/Kook.Net.Core/Entities/Invites/InviteMaxAge.cs +++ b/src/Kook.Net.Core/Entities/Invites/InviteMaxAge.cs @@ -33,4 +33,4 @@ public enum InviteMaxAge /// The invite will expire after one week (604800 seconds). /// _604800 = 604800 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Invites/InviteMaxUses.cs b/src/Kook.Net.Core/Entities/Invites/InviteMaxUses.cs index 471150a5..d3a801d0 100644 --- a/src/Kook.Net.Core/Entities/Invites/InviteMaxUses.cs +++ b/src/Kook.Net.Core/Entities/Invites/InviteMaxUses.cs @@ -33,4 +33,4 @@ public enum InviteMaxUses /// This can be used for 100 times. /// _100 = 100 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/AttachmentType.cs b/src/Kook.Net.Core/Entities/Messages/AttachmentType.cs index 98f423ef..a640b1e7 100644 --- a/src/Kook.Net.Core/Entities/Messages/AttachmentType.cs +++ b/src/Kook.Net.Core/Entities/Messages/AttachmentType.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Specifies the type of the attachment. @@ -21,4 +21,4 @@ public enum AttachmentType /// The attachment is an audio. /// Audio -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Card.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Card.cs index fde2344f..a1b48e03 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Card.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Card.cs @@ -1,4 +1,4 @@ -using System.Collections.Immutable; +using System.Collections.Immutable; using System.Diagnostics; using System.Drawing; @@ -55,7 +55,7 @@ internal Card(CardTheme theme, CardSize size, Color? color, ImmutableArray public ImmutableArray Modules { get; } - + private string DebuggerDisplay => $"{Type} ({Modules.Length} Modules)"; public static bool operator ==(Card left, Card right) @@ -63,7 +63,7 @@ internal Card(CardTheme theme, CardSize size, Color? color, ImmutableArray !(left == right); - + /// Determines whether the specified object is equal to the current . /// If the object passes is an , will be called to compare the 2 instances. /// The object to compare with the current . @@ -76,17 +76,17 @@ public override bool Equals(object obj) /// true if the specified is equal to the current ; otherwise, false. public bool Equals(Card card) => GetHashCode() == card?.GetHashCode(); - + /// public override int GetHashCode() { unchecked { - int hash = (int) 2166136261; + int hash = (int)2166136261; hash = (hash * 16777619) ^ (Type, Theme, Color, Size).GetHashCode(); foreach (IModule module in Modules) hash = (hash * 16777619) ^ module.GetHashCode(); return hash; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/CardBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/CardBuilder.cs index ac9928bf..31c5b978 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/CardBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/CardBuilder.cs @@ -1,4 +1,4 @@ -using System.Collections.Immutable; +using System.Collections.Immutable; namespace Kook; @@ -22,7 +22,7 @@ public CardBuilder() /// A value that represents the type of the card. /// public CardType Type => CardType.Card; - + /// /// Gets or sets the theme of the card. /// @@ -46,7 +46,7 @@ public CardBuilder() /// A value that represents the size of the card. /// public CardSize Size { get; set; } - + /// /// Gets or sets the modules in the card. /// @@ -69,7 +69,7 @@ public CardBuilder WithTheme(CardTheme theme) Theme = theme; return this; } - + /// /// Sets the color displayed along the left side of the card. /// @@ -84,7 +84,7 @@ public CardBuilder WithColor(Color color) Color = color; return this; } - + /// /// Sets the size of the card. /// @@ -99,7 +99,7 @@ public CardBuilder WithSize(CardSize size) Size = size; return this; } - + /// /// Adds a module to the card. /// @@ -144,7 +144,7 @@ public Card Build() => /// ICard ICardBuilder.Build() => Build(); - + public static bool operator ==(CardBuilder left, CardBuilder right) => left?.Equals(right) ?? right is null; @@ -174,7 +174,7 @@ public bool Equals(CardBuilder cardBuilder) && Color == cardBuilder.Color && Size == cardBuilder.Size; } - + /// public override int GetHashCode() => base.GetHashCode(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/CardSize.cs b/src/Kook.Net.Core/Entities/Messages/Cards/CardSize.cs index 8534e28d..56fe9225 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/CardSize.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/CardSize.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Specifies the size of a card. @@ -13,4 +13,4 @@ public enum CardSize /// The card is a large card. /// Large -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/CardTheme.cs b/src/Kook.Net.Core/Entities/Messages/Cards/CardTheme.cs index 699a86da..262b04ad 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/CardTheme.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/CardTheme.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Specifies the theme of the card. @@ -33,4 +33,4 @@ public enum CardTheme : uint /// The card shows like a dark message. /// None -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/CardType.cs b/src/Kook.Net.Core/Entities/Messages/Cards/CardType.cs index 4d3c75c6..c0b28d1a 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/CardType.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/CardType.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Specifies the type of the card. @@ -9,4 +9,4 @@ public enum CardType /// The card is a normal card. /// Card -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonClickEventType.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonClickEventType.cs index 7734938b..5faf23c8 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonClickEventType.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonClickEventType.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Specifies the event type fired when a is clicked. @@ -17,4 +17,4 @@ public enum ButtonClickEventType /// The value of the button's property will be submitted. /// ReturnValue -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonElement.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonElement.cs index ea32e152..5092e4c5 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonElement.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonElement.cs @@ -55,7 +55,7 @@ internal ButtonElement(ButtonTheme theme, string value, ButtonClickEventType cli /// An value that represents the text element of the button. /// public IElement Text { get; } - + private string DebuggerDisplay => $"{Type}: {Text} ({Click}, {Value}, {Theme})"; public static bool operator ==(ButtonElement left, ButtonElement right) @@ -82,10 +82,10 @@ public override int GetHashCode() { unchecked { - int hash = (int) 2166136261; + int hash = (int)2166136261; hash = (hash * 16777619) ^ (Type, Theme, Value, Click).GetHashCode(); hash = (hash * 16777619) ^ Text.GetHashCode(); return hash; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonTheme.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonTheme.cs index 0f5ce58f..a83160df 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonTheme.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ButtonTheme.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Specifies the theme of a . @@ -29,4 +29,4 @@ public enum ButtonTheme /// The button is a secondary button. /// Secondary, -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ElementBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ElementBuilder.cs index 4bfe6057..ee2eb904 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ElementBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ElementBuilder.cs @@ -1,5 +1,5 @@ -using System.Collections.Immutable; using Kook.Utils; +using System.Collections.Immutable; namespace Kook; @@ -25,7 +25,7 @@ public class PlainTextElementBuilder : IElementBuilder, IEquatable that represents the type of element that this builder builds. /// public ElementType Type => ElementType.PlainText; - + /// /// Gets or sets the content of a . /// @@ -81,7 +81,7 @@ public PlainTextElementBuilder WithContent(string content) Content = content; return this; } - + /// /// Sets whether the shortcuts should be translated into emojis. /// @@ -105,7 +105,7 @@ public PlainTextElementBuilder WithEmoji(bool emoji) /// /// A represents the built element object. /// - public PlainTextElement Build() + public PlainTextElement Build() => new PlainTextElement(Content, Emoji); /// @@ -124,9 +124,9 @@ public PlainTextElement Build() /// /// The length of is greater than . /// - public static implicit operator PlainTextElementBuilder(string content) => + public static implicit operator PlainTextElementBuilder(string content) => new PlainTextElementBuilder().WithContent(content); - + /// IElement IElementBuilder.Build() => Build(); @@ -146,7 +146,7 @@ public bool Equals(PlainTextElementBuilder plainTextElementBuilder) { if (plainTextElementBuilder is null) return false; - + return Type == plainTextElementBuilder.Type && Content == plainTextElementBuilder.Content && Emoji == plainTextElementBuilder.Emoji; @@ -227,7 +227,7 @@ public KMarkdownElementBuilder WithContent(string content) /// /// A represents the built element object. /// - public KMarkdownElement Build() + public KMarkdownElement Build() => new KMarkdownElement(Content); /// @@ -246,9 +246,9 @@ public KMarkdownElement Build() /// /// The length of is greater than . /// - public static implicit operator KMarkdownElementBuilder(string content) => + public static implicit operator KMarkdownElementBuilder(string content) => new KMarkdownElementBuilder().WithContent(content); - + /// IElement IElementBuilder.Build() => Build(); @@ -268,7 +268,7 @@ public bool Equals(KMarkdownElementBuilder kMarkdownElementBuilder) { if (kMarkdownElementBuilder is null) return false; - + return Type == kMarkdownElementBuilder.Type && Content == kMarkdownElementBuilder.Content; } @@ -288,7 +288,7 @@ public class ImageElementBuilder : IElementBuilder, IEquatable public const int MaxAlternativeLength = 20; - + /// /// Gets the type of the element that this builder builds. /// @@ -342,7 +342,7 @@ public string Alternative /// or null if whether the image should be rendered as a circle is not specified. /// public bool? Circle { get; set; } - + /// /// Sets the source of an . /// @@ -402,7 +402,7 @@ public ImageElementBuilder WithCircle(bool circle) Circle = circle; return this; } - + /// /// Builds the into an . /// @@ -418,7 +418,7 @@ public ImageElement Build() UrlValidation.Validate(Source); return new ImageElement(Source, Alternative, Size, Circle); } - + /// /// Initialized a new instance of the class /// with the specified content. @@ -434,7 +434,7 @@ public ImageElement Build() /// public static implicit operator ImageElementBuilder(string source) => new ImageElementBuilder() .WithSource(source); - + /// IElement IElementBuilder.Build() => Build(); @@ -454,7 +454,7 @@ public bool Equals(ImageElementBuilder imageElementBuilder) { if (imageElementBuilder is null) return false; - + return Type == imageElementBuilder.Type && Source == imageElementBuilder.Source && Alternative == imageElementBuilder.Alternative @@ -477,7 +477,7 @@ public class ButtonElementBuilder : IElementBuilder, IEquatable public const int MaxButtonTextLength = 40; - + /// /// Gets the type of the element that this builder builds. /// @@ -485,7 +485,7 @@ public class ButtonElementBuilder : IElementBuilder, IEquatable that represents the type of element that this builder builds. /// public ElementType Type => ElementType.Button; - + /// /// Gets or sets the theme of the button. /// @@ -493,7 +493,7 @@ public class ButtonElementBuilder : IElementBuilder, IEquatable that represents the theme of the button. /// public ButtonTheme Theme { get; set; } - + /// /// Gets or sets the value of the button. /// @@ -505,7 +505,7 @@ public class ButtonElementBuilder : IElementBuilder, IEquatable public string Value { get; set; } - + /// /// Gets or sets the type of the click event. /// @@ -660,7 +660,7 @@ public ButtonElementBuilder WithText(string text, bool isKMarkdown = false) }; return this; } - + /// /// Builds the into a . /// @@ -693,7 +693,7 @@ public bool Equals(ButtonElementBuilder buttonElementBuilder) { if (buttonElementBuilder is null) return false; - + return Type == buttonElementBuilder.Type && Theme == buttonElementBuilder.Theme && Value == buttonElementBuilder.Value @@ -733,7 +733,7 @@ public ParagraphStructBuilder() { Fields = new List(); } - + /// /// Gets the type of the element that this builder builds. /// @@ -741,7 +741,7 @@ public ParagraphStructBuilder() /// An that represents the type of element that this builder builds. /// public ElementType Type => ElementType.Paragraph; - + /// /// Gets or sets the number of columns of the paragraph. /// @@ -786,17 +786,19 @@ public List Fields get => _fields; set { - if (value == null) throw new ArgumentNullException( + if (value == null) + throw new ArgumentNullException( paramName: nameof(Fields), message: "Cannot set an paragraph struct builder's fields collection to null."); - if (value.Count > MaxFieldCount) throw new ArgumentException( + if (value.Count > MaxFieldCount) + throw new ArgumentException( message: $"Field count must be less than or equal to {MaxFieldCount}.", paramName: nameof(Fields)); - if (value.Any(field => field is not PlainTextElementBuilder && field is not KMarkdownElementBuilder)) + if (value.Any(field => field is not PlainTextElementBuilder && field is not KMarkdownElementBuilder)) throw new ArgumentException( message: "The elements of fields in a paragraph must be PlainTextElementBuilder or KMarkdownElementBuilder.", paramName: nameof(Fields)); - + _fields = value; } } @@ -829,7 +831,8 @@ public ParagraphStructBuilder WithColumnCount(int count) /// public ParagraphStructBuilder AddField(PlainTextElementBuilder field) { - if (Fields.Count >= MaxFieldCount) throw new ArgumentException( + if (Fields.Count >= MaxFieldCount) + throw new ArgumentException( message: $"Field count must be less than or equal to {MaxFieldCount}.", paramName: nameof(field)); Fields.Add(field); @@ -849,7 +852,8 @@ public ParagraphStructBuilder AddField(PlainTextElementBuilder field) /// public ParagraphStructBuilder AddField(KMarkdownElementBuilder field) { - if (Fields.Count >= MaxFieldCount) throw new ArgumentException( + if (Fields.Count >= MaxFieldCount) + throw new ArgumentException( message: $"Field count must be less than or equal to {MaxFieldCount}.", paramName: nameof(field)); Fields.Add(field); @@ -884,7 +888,7 @@ public ParagraphStructBuilder AddField(Action action = null) throw new ArgumentException( message: "The elements of fields in a paragraph must be PlainTextElementBuilder or KMarkdownElementBuilder.", paramName: nameof(field)); - + } return this; } @@ -895,9 +899,9 @@ public ParagraphStructBuilder AddField(Action action = null) /// /// A represents the built element object. /// - public ParagraphStruct Build() => + public ParagraphStruct Build() => new(ColumnCount, Fields.Select(f => f.Build()).ToImmutableArray()); - + /// IElement IElementBuilder.Build() => Build(); @@ -931,4 +935,4 @@ public bool Equals(ParagraphStructBuilder paragraphStructBuilder) /// public override int GetHashCode() => base.GetHashCode(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ElementType.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ElementType.cs index 2fc3014b..dc655ffe 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ElementType.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ElementType.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Specifies the type of an . @@ -25,4 +25,4 @@ public enum ElementType /// The element is a paragraph struct. /// Paragraph -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/IElement.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/IElement.cs index 1b516152..fe0fe1d1 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/IElement.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/IElement.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// A generic element used in modules. @@ -9,4 +9,4 @@ public interface IElement /// Gets the type of this element. /// ElementType Type { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/IElementBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/IElementBuilder.cs index ed530553..2841fe74 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/IElementBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/IElementBuilder.cs @@ -12,7 +12,7 @@ public interface IElementBuilder /// An that specifies the type of the element to be created. /// ElementType Type { get; } - + /// /// Builds the into an . /// @@ -20,4 +20,4 @@ public interface IElementBuilder /// An represents the built element object. /// IElement Build(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageElement.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageElement.cs index 26ecd745..1b7797f1 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageElement.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageElement.cs @@ -23,7 +23,7 @@ internal ImageElement(string source, string alternative = null, ImageSize? size /// An value that represents the theme of the button. /// public ElementType Type => ElementType.Image; - + /// /// Gets the source of the image. /// @@ -82,4 +82,4 @@ public bool Equals(ImageElement imageElement) /// public override int GetHashCode() => (Type, Source, Alternative, Size, Circle).GetHashCode(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageSize.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageSize.cs index 73517ccc..0b70ea2c 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageSize.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ImageSize.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Specifies the size of the image in . @@ -13,4 +13,4 @@ public enum ImageSize /// The image is displayed at large size. /// Large -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/KMarkdownElement.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/KMarkdownElement.cs index 5b717f1d..f9150182 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/KMarkdownElement.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/KMarkdownElement.cs @@ -54,4 +54,4 @@ public bool Equals(KMarkdownElement kMarkdownElement) /// public override int GetHashCode() => (Type, Content).GetHashCode(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ParagraphStruct.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ParagraphStruct.cs index 6f47cec8..ec3bd438 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ParagraphStruct.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/ParagraphStruct.cs @@ -15,7 +15,7 @@ internal ParagraphStruct(int columnCount, ImmutableArray fields) ColumnCount = columnCount; Fields = fields; } - + /// /// Gets the type of the element. /// @@ -65,11 +65,11 @@ public override int GetHashCode() { unchecked { - int hash = (int) 2166136261; + int hash = (int)2166136261; hash = (hash * 16777619) ^ (Type, ColumnCount).GetHashCode(); foreach (IElement element in Fields) hash = (hash * 16777619) ^ element.GetHashCode(); return hash; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/PlainTextElement.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/PlainTextElement.cs index eb1b580b..bbaaa5a7 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/PlainTextElement.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/PlainTextElement.cs @@ -65,4 +65,4 @@ public bool Equals(PlainTextElement plainTextElement) /// public override int GetHashCode() => (Type, Content, Emoji).GetHashCode(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/TextTheme.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/TextTheme.cs index 67def9a6..3d503f39 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Elements/TextTheme.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Elements/TextTheme.cs @@ -15,4 +15,4 @@ public enum TextTheme : ushort Tips, Pink, Purple -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/ICard.cs b/src/Kook.Net.Core/Entities/Messages/Cards/ICard.cs index a75eeda4..089b9da8 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/ICard.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/ICard.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Represents a generic card. @@ -12,7 +12,7 @@ public interface ICard /// A value that represents the type of the card. /// CardType Type { get; } - + /// /// Gets the number of the modules in this card. /// @@ -20,4 +20,4 @@ public interface ICard /// An value that represents how many modules are in this card. /// int ModuleCount { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/ICardBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/ICardBuilder.cs index bbfba6bc..942f3d9a 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/ICardBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/ICardBuilder.cs @@ -9,7 +9,7 @@ public interface ICardBuilder /// Gets the type of the this builder creates. /// CardType Type { get; } - + /// /// Builds the into an . /// @@ -17,4 +17,4 @@ public interface ICardBuilder /// An represents the built card object. /// ICard Build(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ActionGroupModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ActionGroupModule.cs index 697dc396..ab139988 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ActionGroupModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ActionGroupModule.cs @@ -13,10 +13,10 @@ internal ActionGroupModule(ImmutableArray elements) { Elements = elements; } - + /// public ModuleType Type => ModuleType.ActionGroup; - + /// /// Gets the elements of this module. /// @@ -24,9 +24,9 @@ internal ActionGroupModule(ImmutableArray elements) /// An containing the elements of this module. /// public ImmutableArray Elements { get; } - + private string DebuggerDisplay => $"{Type} ({Elements.Length} Elements)"; - + public static bool operator ==(ActionGroupModule left, ActionGroupModule right) => left?.Equals(right) ?? right is null; @@ -51,11 +51,11 @@ public override int GetHashCode() { unchecked { - int hash = (int) 2166136261; + int hash = (int)2166136261; hash = (hash * 16777619) ^ Type.GetHashCode(); foreach (ButtonElement buttonElement in Elements) hash = (hash * 16777619) ^ buttonElement.GetHashCode(); return hash; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/AudioModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/AudioModule.cs index 7d499db5..371e5285 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/AudioModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/AudioModule.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; namespace Kook; @@ -14,16 +14,16 @@ internal AudioModule(string source, string title, string cover) Title = title; Cover = cover; } - + /// public ModuleType Type => ModuleType.Audio; /// public string Source { get; } - + /// public string Title { get; } - + /// /// Gets the cover of the audio associated with this module. /// @@ -31,9 +31,9 @@ internal AudioModule(string source, string title, string cover) /// A representing the cover of the audio associated with this module. /// public string Cover { get; } - + private string DebuggerDisplay => $"{Type}: {Title}"; - + public static bool operator ==(AudioModule left, AudioModule right) => left?.Equals(right) ?? right is null; @@ -56,4 +56,4 @@ public bool Equals(AudioModule audioModule) /// public override int GetHashCode() => (Type, Source, Title, Cover).GetHashCode(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContainerModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContainerModule.cs index 28e315fc..c50853e2 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContainerModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContainerModule.cs @@ -13,10 +13,10 @@ internal ContainerModule(ImmutableArray elements) { Elements = elements; } - + /// public ModuleType Type => ModuleType.Container; - + /// /// Gets the elements in this container module. /// @@ -24,9 +24,9 @@ internal ContainerModule(ImmutableArray elements) /// An representing the elements in this container module. /// public ImmutableArray Elements { get; } - + private string DebuggerDisplay => $"{Type} ({Elements.Length} Elements)"; - + public static bool operator ==(ContainerModule left, ContainerModule right) => left?.Equals(right) ?? right is null; @@ -51,11 +51,11 @@ public override int GetHashCode() { unchecked { - int hash = (int) 2166136261; + int hash = (int)2166136261; hash = (hash * 16777619) ^ Type.GetHashCode(); foreach (ImageElement element in Elements) hash = (hash * 16777619) ^ element.GetHashCode(); return hash; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContextModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContextModule.cs index db5c39e0..ef5562f8 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContextModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ContextModule.cs @@ -16,7 +16,7 @@ internal ContextModule(ImmutableArray elements) /// public ModuleType Type => ModuleType.Context; - + /// /// Gets the elements in this context module. /// @@ -24,9 +24,9 @@ internal ContextModule(ImmutableArray elements) /// An representing the elements in this context module. /// public ImmutableArray Elements { get; } - + private string DebuggerDisplay => $"{Type} ({Elements.Length} Elements)"; - + public static bool operator ==(ContextModule left, ContextModule right) => left?.Equals(right) ?? right is null; @@ -51,11 +51,11 @@ public override int GetHashCode() { unchecked { - int hash = (int) 2166136261; + int hash = (int)2166136261; hash = (hash * 16777619) ^ Type.GetHashCode(); foreach (IElement element in Elements) hash = (hash * 16777619) ^ element.GetHashCode(); return hash; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownMode.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownMode.cs index 40af7d91..aabdc792 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownMode.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownMode.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Specifies the display mode for the countdown timer. @@ -17,4 +17,4 @@ public enum CountdownMode /// The timer will display the time in seconds. /// Second -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownModule.cs index 734b90c7..ea006085 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/CountdownModule.cs @@ -14,10 +14,10 @@ internal CountdownModule(CountdownMode mode, DateTimeOffset endTime, DateTimeOff EndTime = endTime; StartTime = startTime; } - + /// public ModuleType Type => ModuleType.Countdown; - + /// /// Gets the end time of the countdown. /// @@ -41,9 +41,9 @@ internal CountdownModule(CountdownMode mode, DateTimeOffset endTime, DateTimeOff /// A value that represents the mode of the countdown. /// public CountdownMode Mode { get; } - - private string DebuggerDisplay => $"{Type}: To {EndTime:yyyy'/'M'/'d HH:mm:ss z} ({Mode} Mode{(StartTime is null? string.Empty: $", From {EndTime:yyyy'/'M'/'d HH:mm:ss z}")})"; - + + private string DebuggerDisplay => $"{Type}: To {EndTime:yyyy'/'M'/'d HH:mm:ss z} ({Mode} Mode{(StartTime is null ? string.Empty : $", From {EndTime:yyyy'/'M'/'d HH:mm:ss z}")})"; + public static bool operator ==(CountdownModule left, CountdownModule right) => left?.Equals(right) ?? right is null; @@ -66,4 +66,4 @@ public bool Equals(CountdownModule countdownModule) /// public override int GetHashCode() => (Type, EndTime, StartTime, Mode).GetHashCode(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/DividerModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/DividerModule.cs index 49245305..0eebe676 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/DividerModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/DividerModule.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; namespace Kook; @@ -10,14 +10,14 @@ public class DividerModule : IModule, IEquatable { internal DividerModule() { - + } - + /// public ModuleType Type => ModuleType.Divider; - + private string DebuggerDisplay => $"{Type}"; - + public static bool operator ==(DividerModule left, DividerModule right) => left?.Equals(right) ?? right is null; @@ -40,4 +40,4 @@ public bool Equals(DividerModule dividerModule) /// public override int GetHashCode() => Type.GetHashCode(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/FileModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/FileModule.cs index 185930ef..896debcf 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/FileModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/FileModule.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; namespace Kook; @@ -19,12 +19,12 @@ internal FileModule(string source, string title) /// public string Source { get; } - + /// public string Title { get; } - + private string DebuggerDisplay => $"{Type}: {Title}"; - + public static bool operator ==(FileModule left, FileModule right) => left?.Equals(right) ?? right is null; @@ -47,4 +47,4 @@ public bool Equals(FileModule fileModule) /// public override int GetHashCode() => (Type, Source, Title).GetHashCode(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/HeaderModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/HeaderModule.cs index d5a75da2..c76f4dc9 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/HeaderModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/HeaderModule.cs @@ -23,10 +23,10 @@ internal HeaderModule(PlainTextElement text) /// A representing the text of the header. /// public PlainTextElement Text { get; } - + public override string ToString() => Text.ToString(); private string DebuggerDisplay => $"{Type}: {Text}"; - + public static bool operator ==(HeaderModule left, HeaderModule right) => left?.Equals(right) ?? right is null; @@ -51,10 +51,10 @@ public override int GetHashCode() { unchecked { - int hash = (int) 2166136261; + int hash = (int)2166136261; hash = (hash * 16777619) ^ Type.GetHashCode(); hash = (hash * 16777619) ^ Text.GetHashCode(); return hash; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IMediaModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IMediaModule.cs index 6a9964a3..cfc7c5dd 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IMediaModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IMediaModule.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// A generic media module that can be used in an . @@ -20,4 +20,4 @@ public interface IMediaModule : IModule /// A representing the title of the media associated with this module. /// string Title { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IModule.cs index 122a01f6..735b9840 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IModule.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; public interface IModule { @@ -9,4 +9,4 @@ public interface IModule /// A value that represents the type of the module. /// ModuleType Type { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IModuleBuilder.cs index 17a7ff2a..ec61480d 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/IModuleBuilder.cs @@ -12,7 +12,7 @@ public interface IModuleBuilder /// A representing the module type of the this builder creates. /// ModuleType Type { get; } - + /// /// Builds the into an . /// @@ -20,4 +20,4 @@ public interface IModuleBuilder /// An representing the built module object. /// IModule Build(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ImageGroupModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ImageGroupModule.cs index de485789..9fc63764 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ImageGroupModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ImageGroupModule.cs @@ -13,8 +13,8 @@ internal ImageGroupModule(ImmutableArray elements) { Elements = elements; } - - /// + + /// public ModuleType Type => ModuleType.ImageGroup; /// @@ -24,9 +24,9 @@ internal ImageGroupModule(ImmutableArray elements) /// An representing the images in this image group module. /// public ImmutableArray Elements { get; } - + private string DebuggerDisplay => $"{Type} ({Elements.Length} Elements)"; - + public static bool operator ==(ImageGroupModule left, ImageGroupModule right) => left?.Equals(right) ?? right is null; @@ -51,11 +51,11 @@ public override int GetHashCode() { unchecked { - int hash = (int) 2166136261; + int hash = (int)2166136261; hash = (hash * 16777619) ^ Type.GetHashCode(); foreach (ImageElement element in Elements) hash = (hash * 16777619) ^ element.GetHashCode(); return hash; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/InviteModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/InviteModule.cs index 20c128d5..4dabbf0a 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/InviteModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/InviteModule.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; namespace Kook; @@ -17,9 +17,9 @@ internal InviteModule(string code) public ModuleType Type => ModuleType.Invite; public string Code { get; } - + private string DebuggerDisplay => $"{Type}: {Code}"; - + public static bool operator ==(InviteModule left, InviteModule right) => left?.Equals(right) ?? right is null; @@ -42,4 +42,4 @@ public bool Equals(InviteModule inviteModule) /// public override int GetHashCode() => (Type, Code).GetHashCode(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ModuleBuilder.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ModuleBuilder.cs index 6f6b84e1..bbd0e7d8 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ModuleBuilder.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ModuleBuilder.cs @@ -1,5 +1,5 @@ -using System.Collections.Immutable; using Kook.Utils; +using System.Collections.Immutable; namespace Kook; @@ -100,9 +100,9 @@ public HeaderModuleBuilder WithText(Action action) /// /// An object that is initialized with the specified . /// - public static implicit operator HeaderModuleBuilder(string text) + public static implicit operator HeaderModuleBuilder(string text) => new HeaderModuleBuilder().WithText(b => b.WithContent(text)); - + /// IModule IModuleBuilder.Build() => Build(); @@ -150,7 +150,7 @@ public class SectionModuleBuilder : IModuleBuilder, IEquatable is positioned relative to the . /// public SectionAccessoryMode Mode { get; set; } - + /// /// Gets or sets the text of the section. /// @@ -195,7 +195,7 @@ public IElementBuilder Accessory _accessory = value; } } - + /// /// Sets the text of the section. /// @@ -1010,7 +1010,7 @@ public bool Equals(DividerModuleBuilder dividerModuleBuilder) { if (dividerModuleBuilder is null) return false; - + return Type == dividerModuleBuilder.Type; } @@ -1033,7 +1033,7 @@ public class FileModuleBuilder : IModuleBuilder, IEquatable /// The source URL of the file. /// public string Source { get; set; } - + /// /// Gets or sets the title of the file. /// @@ -1110,7 +1110,7 @@ public bool Equals(FileModuleBuilder fileModuleBuilder) { if (fileModuleBuilder is null) return false; - + return Type == fileModuleBuilder.Type && Source == fileModuleBuilder.Source && Title == fileModuleBuilder.Title; @@ -1135,7 +1135,7 @@ public class VideoModuleBuilder : IModuleBuilder, IEquatable /// The source URL of the video. /// public string Source { get; set; } - + /// /// Gets or sets the title of the video. /// @@ -1212,7 +1212,7 @@ public bool Equals(VideoModuleBuilder videoModuleBuilder) { if (videoModuleBuilder is null) return false; - + return Type == videoModuleBuilder.Type && Source == videoModuleBuilder.Source && Title == videoModuleBuilder.Title; @@ -1237,7 +1237,7 @@ public class AudioModuleBuilder : IModuleBuilder, IEquatable /// The source URL of the video. /// public string Source { get; set; } - + /// /// Gets or sets the cover URL of the video. /// @@ -1245,7 +1245,7 @@ public class AudioModuleBuilder : IModuleBuilder, IEquatable /// The cover URL of the video. /// public string Cover { get; set; } - + /// /// Gets or sets the title of the video. /// @@ -1344,7 +1344,7 @@ public bool Equals(AudioModuleBuilder audioModuleBuilder) { if (audioModuleBuilder is null) return false; - + return Type == audioModuleBuilder.Type && Source == audioModuleBuilder.Source && Title == audioModuleBuilder.Title @@ -1484,7 +1484,7 @@ public bool Equals(CountdownModuleBuilder countdownModuleBuilder) { if (countdownModuleBuilder is null) return false; - + return Type == countdownModuleBuilder.Type && EndTime == countdownModuleBuilder.EndTime && StartTime == countdownModuleBuilder.StartTime @@ -1567,11 +1567,11 @@ public bool Equals(InviteModuleBuilder inviteModuleBuilder) { if (inviteModuleBuilder is null) return false; - + return Type == inviteModuleBuilder.Type && Code == inviteModuleBuilder.Code; } /// public override int GetHashCode() => base.GetHashCode(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ModuleType.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ModuleType.cs index d0bf676b..13041f28 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ModuleType.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/ModuleType.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Specifies the type of an . @@ -53,4 +53,4 @@ public enum ModuleType /// An . /// Invite -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionAccessoryMode.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionAccessoryMode.cs index 1d26d083..6c86be2d 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionAccessoryMode.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionAccessoryMode.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Specifies the accessory position relative to the text element. @@ -17,4 +17,4 @@ public enum SectionAccessoryMode /// The accessory is positioned to the right of the text element. /// Right -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionModule.cs index bb30fc7f..09a8b9ad 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/SectionModule.cs @@ -43,9 +43,9 @@ internal SectionModule(SectionAccessoryMode mode, IElement text, IElement access /// An representing the accessory of the section. /// public IElement Accessory { get; } - + private string DebuggerDisplay => $"{Type}: {Text}{(Accessory is null ? string.Empty : $"{Mode} Accessory")}"; - + public static bool operator ==(SectionModule left, SectionModule right) => left?.Equals(right) ?? right is null; @@ -70,11 +70,11 @@ public override int GetHashCode() { unchecked { - int hash = (int) 2166136261; + int hash = (int)2166136261; hash = (hash * 16777619) ^ (Type, Mode).GetHashCode(); hash = (hash * 16777619) ^ Text.GetHashCode(); hash = (hash * 16777619) ^ Accessory.GetHashCode(); return hash; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/VideoModule.cs b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/VideoModule.cs index 6a3b5e45..2ca64b97 100644 --- a/src/Kook.Net.Core/Entities/Messages/Cards/Modules/VideoModule.cs +++ b/src/Kook.Net.Core/Entities/Messages/Cards/Modules/VideoModule.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; namespace Kook; @@ -19,12 +19,12 @@ internal VideoModule(string source, string title) /// public string Source { get; } - + /// public string Title { get; } - + private string DebuggerDisplay => $"{Type}: {Title}"; - + public static bool operator ==(VideoModule left, VideoModule right) => left?.Equals(right) ?? right is null; @@ -47,4 +47,4 @@ public bool Equals(VideoModule videoModule) /// public override int GetHashCode() => (Type, Source, Title).GetHashCode(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/CreateAttachmentMode.cs b/src/Kook.Net.Core/Entities/Messages/CreateAttachmentMode.cs index bb4497b5..a7a862b3 100644 --- a/src/Kook.Net.Core/Entities/Messages/CreateAttachmentMode.cs +++ b/src/Kook.Net.Core/Entities/Messages/CreateAttachmentMode.cs @@ -9,15 +9,15 @@ public enum CreateAttachmentMode /// The will be created via a local file path. /// FilePath, - + /// /// The will be created via a . /// Stream, - + /// /// The will be created via a /// pointing to a file on KOOK asset OSS. /// AssetUri -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Embeds/BilibiliVideoEmbed.cs b/src/Kook.Net.Core/Entities/Messages/Embeds/BilibiliVideoEmbed.cs index 32b8483a..4dd4e57c 100644 --- a/src/Kook.Net.Core/Entities/Messages/Embeds/BilibiliVideoEmbed.cs +++ b/src/Kook.Net.Core/Entities/Messages/Embeds/BilibiliVideoEmbed.cs @@ -12,9 +12,9 @@ public BilibiliVideoEmbed(string url, string originUrl, string bvNumber, string Title = title; Cover = cover; } - + public EmbedType Type => EmbedType.Link; - + public string Url { get; internal set; } public string OriginUrl { get; internal set; } @@ -28,4 +28,4 @@ public BilibiliVideoEmbed(string url, string originUrl, string bvNumber, string public string Title { get; internal set; } public string Cover { get; internal set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Embeds/EmbedType.cs b/src/Kook.Net.Core/Entities/Messages/Embeds/EmbedType.cs index 37f98163..e8f95492 100644 --- a/src/Kook.Net.Core/Entities/Messages/Embeds/EmbedType.cs +++ b/src/Kook.Net.Core/Entities/Messages/Embeds/EmbedType.cs @@ -7,4 +7,4 @@ public enum EmbedType Image, BilibiliVideo // TODO: To be investigated -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Embeds/IEmbed.cs b/src/Kook.Net.Core/Entities/Messages/Embeds/IEmbed.cs index b346818c..99838830 100644 --- a/src/Kook.Net.Core/Entities/Messages/Embeds/IEmbed.cs +++ b/src/Kook.Net.Core/Entities/Messages/Embeds/IEmbed.cs @@ -13,7 +13,7 @@ public interface IEmbed /// A that represents the type of this embed. /// EmbedType Type { get; } - + /// /// Gets the URL of this embed. /// @@ -21,4 +21,4 @@ public interface IEmbed /// A that represents the URL of this embed. /// string Url { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Embeds/ImageEmbed.cs b/src/Kook.Net.Core/Entities/Messages/Embeds/ImageEmbed.cs index 4ac6d248..7230c0b0 100644 --- a/src/Kook.Net.Core/Entities/Messages/Embeds/ImageEmbed.cs +++ b/src/Kook.Net.Core/Entities/Messages/Embeds/ImageEmbed.cs @@ -10,10 +10,10 @@ internal ImageEmbed(string url, string originUrl) Url = url; OriginUrl = originUrl; } - + /// public EmbedType Type => EmbedType.Link; - + /// public string Url { get; internal set; } @@ -24,4 +24,4 @@ internal ImageEmbed(string url, string originUrl) /// A representing the original URL of the image. /// public string OriginUrl { get; internal set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Embeds/LinkEmbed.cs b/src/Kook.Net.Core/Entities/Messages/Embeds/LinkEmbed.cs index ed13a8bc..85aed208 100644 --- a/src/Kook.Net.Core/Entities/Messages/Embeds/LinkEmbed.cs +++ b/src/Kook.Net.Core/Entities/Messages/Embeds/LinkEmbed.cs @@ -14,10 +14,10 @@ internal LinkEmbed(string url, string title, string description, string siteName Color = color; Image = image; } - + /// public EmbedType Type => EmbedType.Link; - + /// public string Url { get; internal set; } @@ -60,4 +60,4 @@ internal LinkEmbed(string url, string title, string description, string siteName /// A representing the URL of the image related to the website the link directs to. /// public string Image { get; internal set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Embeds/NotImplementedEmbed.cs b/src/Kook.Net.Core/Entities/Messages/Embeds/NotImplementedEmbed.cs index 906aa9e3..6ee80964 100644 --- a/src/Kook.Net.Core/Entities/Messages/Embeds/NotImplementedEmbed.cs +++ b/src/Kook.Net.Core/Entities/Messages/Embeds/NotImplementedEmbed.cs @@ -30,10 +30,10 @@ internal NotImplementedEmbed(string rawType, JsonNode jsonNode) /// This value originally came from the type field of the . /// public string RawType { get; internal set; } - + /// public string Url { get; internal set; } - + /// /// Gets the raw JSON of the embed. /// @@ -65,7 +65,7 @@ public T Resolve(JsonSerializerOptions options = null) T embed = JsonNode.Deserialize(options); return embed; } - + /// /// Resolves the embed to a concrete type via delegate. /// @@ -84,4 +84,4 @@ public T Resolve(Func resolvingFunc) T embed = resolvingFunc(this); return embed; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/FileAttachment.cs b/src/Kook.Net.Core/Entities/Messages/FileAttachment.cs index f44c1cc2..f05577ab 100644 --- a/src/Kook.Net.Core/Entities/Messages/FileAttachment.cs +++ b/src/Kook.Net.Core/Entities/Messages/FileAttachment.cs @@ -10,7 +10,7 @@ public struct FileAttachment : IDisposable /// Gets how this attachment will be operated. /// public CreateAttachmentMode Mode { get; private set; } - + /// /// Gets the type of this attachment. /// @@ -133,4 +133,4 @@ public void Dispose() _isDisposed = true; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/IAttachment.cs b/src/Kook.Net.Core/Entities/Messages/IAttachment.cs index cc81c551..35c59658 100644 --- a/src/Kook.Net.Core/Entities/Messages/IAttachment.cs +++ b/src/Kook.Net.Core/Entities/Messages/IAttachment.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Represents a message attachment found in a . @@ -37,7 +37,7 @@ public interface IAttachment /// null if the file size is unknown or not applicable. /// int? Size { get; } - + /// /// Gets the file type of the attachment. /// @@ -46,7 +46,7 @@ public interface IAttachment /// null if the file type is unknown or not applicable. /// string FileType { get; } - + /// /// Gets the duration of the attachment. /// @@ -55,7 +55,7 @@ public interface IAttachment /// null if the duration is unknown or not applicable. /// TimeSpan? Duration { get; } - + /// /// Gets the width of the attachment. /// @@ -64,7 +64,7 @@ public interface IAttachment /// null if the width is unknown or not applicable. /// int? Width { get; } - + /// /// Gets the height of the attachment. /// @@ -73,4 +73,4 @@ public interface IAttachment /// null if the height is unknown or not applicable. /// int? Height { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/IMessage.cs b/src/Kook.Net.Core/Entities/Messages/IMessage.cs index f534fb68..7e705c47 100644 --- a/src/Kook.Net.Core/Entities/Messages/IMessage.cs +++ b/src/Kook.Net.Core/Entities/Messages/IMessage.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Represents a message object. @@ -11,12 +11,12 @@ public interface IMessage : IEntity, IDeletable /// Gets the type of this message. /// MessageType Type { get; } - + /// /// Gets the source type of this message. /// MessageSource Source { get; } - + /// /// Gets the value that indicates whether this message is pinned. /// @@ -24,17 +24,17 @@ public interface IMessage : IEntity, IDeletable /// true if this message was added to its channel's pinned messages; otherwise false. /// bool? IsPinned { get; } - + /// /// Gets the source channel of the message. /// IMessageChannel Channel { get; } - + /// /// Gets the author of this message. /// IUser Author { get; } - + /// /// Gets the content for this message. /// @@ -43,7 +43,7 @@ public interface IMessage : IEntity, IDeletable /// note that this field may be empty or the original code if the message is not a text based message. /// string Content { get; } - + /// /// Gets the clean content for this message. /// @@ -52,7 +52,7 @@ public interface IMessage : IEntity, IDeletable /// note that this field may be empty or the original code if the message is not a text based message. /// string CleanContent { get; } - + /// /// Gets the time this message was sent. /// @@ -60,7 +60,7 @@ public interface IMessage : IEntity, IDeletable /// Time of when the message was sent. /// DateTimeOffset Timestamp { get; } - + /// /// Gets the time of this message's last edit. /// @@ -69,7 +69,7 @@ public interface IMessage : IEntity, IDeletable /// null if the message is never edited. /// DateTimeOffset? EditedTimestamp { get; } - + /// /// Gets the IDs of users mentioned in this message. /// @@ -77,7 +77,7 @@ public interface IMessage : IEntity, IDeletable /// A read-only collection of user IDs. /// IReadOnlyCollection MentionedUserIds { get; } - + /// /// Gets the IDs of roles mentioned in this message. /// @@ -85,7 +85,7 @@ public interface IMessage : IEntity, IDeletable /// A read-only collection of role IDs. /// IReadOnlyCollection MentionedRoleIds { get; } - + /// /// Gets the value that indicates whether this message mentioned everyone. /// @@ -93,7 +93,7 @@ public interface IMessage : IEntity, IDeletable /// true if this message mentioned everyone; otherwise false. /// bool? MentionedEveryone { get; } - + /// /// Gets the value that indicates whether this message mentioned online users. /// @@ -101,12 +101,12 @@ public interface IMessage : IEntity, IDeletable /// true if this message mentioned online users; otherwise false. /// bool? MentionedHere { get; } - + /// /// Gets all tags included in this message's content. /// IReadOnlyCollection Tags { get; } - + /// /// Gets the attachment included in this message. /// @@ -114,7 +114,7 @@ public interface IMessage : IEntity, IDeletable /// The attachment included in this message; /// IReadOnlyCollection Attachments { get; } - + /// /// Gets all cards included in this message. /// @@ -122,7 +122,7 @@ public interface IMessage : IEntity, IDeletable /// A read-only collection of card objects. /// IReadOnlyCollection Cards { get; } - + /// /// Gets all embeds included in this message. /// @@ -130,7 +130,7 @@ public interface IMessage : IEntity, IDeletable /// A read-only collection of embed objects. /// IReadOnlyCollection Embeds { get; } - + /// /// Gets all poke actions included in this message. /// @@ -138,16 +138,16 @@ public interface IMessage : IEntity, IDeletable /// A read-only collection of poke actions objects. /// IReadOnlyCollection Pokes { get; } - + #endregion #region Reactions - + /// /// Gets all reactions included in this message. /// IReadOnlyDictionary Reactions { get; } - + /// /// Adds a reaction to this message. /// @@ -180,7 +180,7 @@ public interface IMessage : IEntity, IDeletable /// /// Task RemoveReactionAsync(IEmote emote, ulong userId, RequestOptions options = null); - + /// /// Gets all users that reacted to a message with a given emote. /// @@ -190,6 +190,6 @@ public interface IMessage : IEntity, IDeletable /// Collection of users. /// Task> GetReactionUsersAsync(IEmote emote, RequestOptions options = null); - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/IQuote.cs b/src/Kook.Net.Core/Entities/Messages/IQuote.cs index ea5d866c..bd8fdfbe 100644 --- a/src/Kook.Net.Core/Entities/Messages/IQuote.cs +++ b/src/Kook.Net.Core/Entities/Messages/IQuote.cs @@ -9,12 +9,12 @@ public interface IQuote : IEntity /// Gets the identifier of the message this quote refers to. /// Guid QuotedMessageId { get; } - + /// /// Gets the type of the message this quote refers to. /// MessageType Type { get; } - + /// /// Gets the content of the message this quote refers to. /// @@ -23,7 +23,7 @@ public interface IQuote : IEntity /// note that this field may be empty or the original code if the message is not a text based message. /// string Content { get; } - + /// /// Gets the time this message was sent. /// @@ -31,9 +31,9 @@ public interface IQuote : IEntity /// Time of when the message was sent. /// DateTimeOffset CreateAt { get; } - + /// /// Gets the author of this message. /// IUser Author { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/IReaction.cs b/src/Kook.Net.Core/Entities/Messages/IReaction.cs index 3cd1a3ce..d6aebff2 100644 --- a/src/Kook.Net.Core/Entities/Messages/IReaction.cs +++ b/src/Kook.Net.Core/Entities/Messages/IReaction.cs @@ -9,4 +9,4 @@ public interface IReaction /// The used in the reaction. /// IEmote Emote { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/ISystemMessage.cs b/src/Kook.Net.Core/Entities/Messages/ISystemMessage.cs index 7354cbee..b4fc15bb 100644 --- a/src/Kook.Net.Core/Entities/Messages/ISystemMessage.cs +++ b/src/Kook.Net.Core/Entities/Messages/ISystemMessage.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Represents a generic message sent by the system. @@ -16,4 +16,4 @@ public interface ISystemMessage : IMessage /// /// SystemMessageType SystemMessageType { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/ITag.cs b/src/Kook.Net.Core/Entities/Messages/ITag.cs index 26cb29e8..460138dd 100644 --- a/src/Kook.Net.Core/Entities/Messages/ITag.cs +++ b/src/Kook.Net.Core/Entities/Messages/ITag.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Gets a generic tag found in messages. @@ -10,24 +10,24 @@ public interface ITag /// Gets position of the tag in the message. /// int Index { get; } - + /// /// Gets the length of the tag. /// int Length { get; } - + /// /// Gets the type of the tag. /// TagType Type { get; } - + /// /// Gets the key of the tag. /// dynamic Key { get; } - + /// /// Gets the value of the tag. /// object Value { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/IUserMessage.cs b/src/Kook.Net.Core/Entities/Messages/IUserMessage.cs index f3d8a60c..89a01d02 100644 --- a/src/Kook.Net.Core/Entities/Messages/IUserMessage.cs +++ b/src/Kook.Net.Core/Entities/Messages/IUserMessage.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Represents a generic message sent by a user. @@ -12,7 +12,7 @@ public interface IUserMessage : IMessage /// The message quote. /// IQuote Quote { get; } - + /// /// Modifies this message. /// @@ -41,5 +41,5 @@ string Resolve( TagHandling roleHandling = TagHandling.Name, TagHandling everyoneHandling = TagHandling.Ignore, TagHandling emojiHandling = TagHandling.Name); - -} \ No newline at end of file + +} diff --git a/src/Kook.Net.Core/Entities/Messages/MessageProperties.cs b/src/Kook.Net.Core/Entities/Messages/MessageProperties.cs index 56ba9b1e..da7a371f 100644 --- a/src/Kook.Net.Core/Entities/Messages/MessageProperties.cs +++ b/src/Kook.Net.Core/Entities/Messages/MessageProperties.cs @@ -28,4 +28,4 @@ public class MessageProperties /// Gets or sets the only user that can see this message. /// public IUser EphemeralUser { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/MessageType.cs b/src/Kook.Net.Core/Entities/Messages/MessageType.cs index f699d145..0f8c8a46 100644 --- a/src/Kook.Net.Core/Entities/Messages/MessageType.cs +++ b/src/Kook.Net.Core/Entities/Messages/MessageType.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; public enum MessageType { @@ -38,4 +38,4 @@ public enum MessageType /// 系统消息 /// System = 255 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/IPoke.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/IPoke.cs index bd51d78d..c81731c7 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/IPoke.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/IPoke.cs @@ -49,4 +49,4 @@ public interface IPoke : IEntity /// Gets how the poke can be used and displayed in message contexts. /// IReadOnlyDictionary MessageScenarios { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/IPokeAction.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/IPokeAction.cs index 1ecf123c..668b11fd 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/IPokeAction.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/IPokeAction.cs @@ -19,4 +19,4 @@ public interface IPokeAction /// Gets the poke this action is associated with. /// IPoke Poke { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeIcon.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeIcon.cs index 8544b31f..b0457885 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeIcon.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeIcon.cs @@ -21,4 +21,4 @@ public PokeIcon(string resource, string resourceExpired) } public static PokeIcon Create(string resource, string resourceExpired) => new(resource, resourceExpired); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeLabel.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeLabel.cs index e9fecef2..4f2a81b5 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeLabel.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeLabel.cs @@ -6,7 +6,7 @@ namespace Kook; public struct PokeLabel : IEntity { public uint Id { get; internal set; } - + public string Name { get; internal set; } internal PokeLabel(uint id, string name) @@ -16,4 +16,4 @@ internal PokeLabel(uint id, string name) } internal static PokeLabel Create(uint id, string name) => new(id, name); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeQuality.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeQuality.cs index 533287c9..3bc943c3 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeQuality.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeQuality.cs @@ -3,9 +3,9 @@ namespace Kook; public struct PokeQuality : IEntity { public uint Id { get; internal set; } - + public Color Color { get; internal set; } - + public IReadOnlyDictionary Resources { get; internal set; } public PokeQuality(uint id, Color color, IReadOnlyDictionary resources) @@ -14,7 +14,7 @@ public PokeQuality(uint id, Color color, IReadOnlyDictionary res Color = color; Resources = resources; } - - public static PokeQuality Create(uint id, Color color, IReadOnlyDictionary resources) + + public static PokeQuality Create(uint id, Color color, IReadOnlyDictionary resources) => new PokeQuality(id, color, resources); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/IPokeResource.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/IPokeResource.cs index adeea8b8..c39bb8f4 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/IPokeResource.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/IPokeResource.cs @@ -9,4 +9,4 @@ public interface IPokeResource /// Gets the type of the poke resource. /// PokeResourceType Type { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/ImageAnimationPokeResource.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/ImageAnimationPokeResource.cs index 6ede044e..97886a8f 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/ImageAnimationPokeResource.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/ImageAnimationPokeResource.cs @@ -16,17 +16,17 @@ public ImageAnimationPokeResource(IReadOnlyDictionary resources, /// public PokeResourceType Type => PokeResourceType.ImageAnimation; - + /// /// Gets the resources of the image animation. /// public IReadOnlyDictionary Resources { get; internal set; } - + /// /// Gets how long this animation animation should last filling the full screen. /// public TimeSpan Duration { get; internal set; } - + /// /// Gets the width of the image animation. /// @@ -36,9 +36,9 @@ public ImageAnimationPokeResource(IReadOnlyDictionary resources, /// Gets the height of the image animation. /// public int Height { get; internal set; } - + /// /// // TODO: To be documented. /// public double Percent { get; internal set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/NotImplementedPokeResource.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/NotImplementedPokeResource.cs index e96af516..2884db2a 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/NotImplementedPokeResource.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/NotImplementedPokeResource.cs @@ -12,10 +12,10 @@ internal NotImplementedPokeResource(string rawType, JsonNode jsonNode) RawType = rawType; JsonNode = jsonNode; } - + /// public PokeResourceType Type => PokeResourceType.NotImplemented; - + /// /// Gets the type of the poke resource. /// @@ -26,7 +26,7 @@ internal NotImplementedPokeResource(string rawType, JsonNode jsonNode) /// This value originally came from the type field of the . /// public string RawType { get; internal set; } - + /// /// Gets the raw JSON of the embed. /// @@ -34,7 +34,7 @@ internal NotImplementedPokeResource(string rawType, JsonNode jsonNode) /// A JsonNode representing the raw JSON of the embed. /// public JsonNode JsonNode { get; internal set; } - + /// /// Resolves the embed to a concrete type via JSON deserialization. /// @@ -58,7 +58,7 @@ public T Resolve(JsonSerializerOptions options = null) T pokeResource = JsonNode.Deserialize(options); return pokeResource; } - + /// /// Resolves the embed to a concrete type via delegate. /// @@ -77,4 +77,4 @@ public T Resolve(Func resolvingFunc) T pokeResource = resolvingFunc(this); return pokeResource; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/PokeResourceType.cs b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/PokeResourceType.cs index bc66d98f..c0ae43bb 100644 --- a/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/PokeResourceType.cs +++ b/src/Kook.Net.Core/Entities/Messages/Pokes/PokeResources/PokeResourceType.cs @@ -4,4 +4,4 @@ public enum PokeResourceType { NotImplemented, ImageAnimation -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/Quote.cs b/src/Kook.Net.Core/Entities/Messages/Quote.cs index 3970ba1b..4225903c 100644 --- a/src/Kook.Net.Core/Entities/Messages/Quote.cs +++ b/src/Kook.Net.Core/Entities/Messages/Quote.cs @@ -23,7 +23,7 @@ public class Quote : IQuote /// Used to delete a quote when modifying a message. /// public Quote Empty => new Quote(Guid.Empty); - + /// /// Initializes a new instance of the class. /// @@ -34,7 +34,7 @@ public Quote(Guid quotedMessageId) { QuotedMessageId = quotedMessageId; } - + internal Quote(string id, Guid quotedMessageId, MessageType type, string content, DateTimeOffset createAt, IUser author) { Id = id; @@ -48,4 +48,4 @@ internal Quote(string id, Guid quotedMessageId, MessageType type, string content internal static Quote Create(string id, Guid quotedMessageId, MessageType type, string content, DateTimeOffset createAt, IUser author) => new Quote(id, quotedMessageId, type, content, createAt, author); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/ReactionMetadata.cs b/src/Kook.Net.Core/Entities/Messages/ReactionMetadata.cs index 65bb3ca8..bfadc982 100644 --- a/src/Kook.Net.Core/Entities/Messages/ReactionMetadata.cs +++ b/src/Kook.Net.Core/Entities/Messages/ReactionMetadata.cs @@ -20,4 +20,4 @@ public struct ReactionMetadata /// true if the user has reacted to the message; otherwise false. /// public bool IsMe { get; internal set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/SystemMessageType.cs b/src/Kook.Net.Core/Entities/Messages/SystemMessageType.cs index 533afc2a..b5c5cbca 100644 --- a/src/Kook.Net.Core/Entities/Messages/SystemMessageType.cs +++ b/src/Kook.Net.Core/Entities/Messages/SystemMessageType.cs @@ -1,9 +1,9 @@ -namespace Kook; +namespace Kook; /// /// Gets the type of a /// public enum SystemMessageType { - -} \ No newline at end of file + +} diff --git a/src/Kook.Net.Core/Entities/Messages/Tag.cs b/src/Kook.Net.Core/Entities/Messages/Tag.cs index 2f1e61ef..92d5f435 100644 --- a/src/Kook.Net.Core/Entities/Messages/Tag.cs +++ b/src/Kook.Net.Core/Entities/Messages/Tag.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; namespace Kook; @@ -16,7 +16,7 @@ public class Tag : ITag public int Length { get; } /// public dynamic Key { get; } - + /// /// Gets the value of the tag. /// @@ -41,4 +41,4 @@ internal Tag(TagType type, int index, int length, dynamic key, T value) /// object ITag.Value => Value; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/TagHandling.cs b/src/Kook.Net.Core/Entities/Messages/TagHandling.cs index 098d3bf4..6de65599 100644 --- a/src/Kook.Net.Core/Entities/Messages/TagHandling.cs +++ b/src/Kook.Net.Core/Entities/Messages/TagHandling.cs @@ -35,4 +35,4 @@ public enum TagHandling /// Sanitizes the tag (e.g. <@53905483156684800> -> <@53905483156684800> (w/ nbsp)). /// Sanitize -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/TagMode.cs b/src/Kook.Net.Core/Entities/Messages/TagMode.cs index 5b42eebb..ade8fe0b 100644 --- a/src/Kook.Net.Core/Entities/Messages/TagMode.cs +++ b/src/Kook.Net.Core/Entities/Messages/TagMode.cs @@ -13,4 +13,4 @@ public enum TagMode /// Parse tags as KMarkdown. /// KMarkdown -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Messages/TagType.cs b/src/Kook.Net.Core/Entities/Messages/TagType.cs index c084d7b8..47fd8f31 100644 --- a/src/Kook.Net.Core/Entities/Messages/TagType.cs +++ b/src/Kook.Net.Core/Entities/Messages/TagType.cs @@ -15,4 +15,4 @@ public enum TagType HereMention, /// The object is an emoji. Emoji -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Permissions/ChannelPermission.cs b/src/Kook.Net.Core/Entities/Permissions/ChannelPermission.cs index acd0644a..46ee8476 100644 --- a/src/Kook.Net.Core/Entities/Permissions/ChannelPermission.cs +++ b/src/Kook.Net.Core/Entities/Permissions/ChannelPermission.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; [Flags] public enum ChannelPermission : uint @@ -6,77 +6,77 @@ public enum ChannelPermission : uint /// /// Allows creation of invites. /// - CreateInvites = 1 << 3, + CreateInvites = 1 << 3, /// /// Allows management and editing of channels. /// - ManageChannels = 1 << 5, + ManageChannels = 1 << 5, /// /// Allows management and editing of roles. /// - ManageRoles = 1 << 10, + ManageRoles = 1 << 10, /// /// Allows guild members to view a channel, which includes reading messages in text channels. /// - ViewChannel = 1 << 11, + ViewChannel = 1 << 11, /// /// Allows for sending messages in a channel /// - SendMessages = 1 << 12, + SendMessages = 1 << 12, /// /// Allows for deletion of other users messages. /// - ManageMessages = 1 << 13, + ManageMessages = 1 << 13, /// /// Allows for uploading images and files. /// - AttachFiles = 1 << 14, + AttachFiles = 1 << 14, /// /// Allows for joining of a voice channel. /// - Connect = 1 << 15, + Connect = 1 << 15, /// /// Allows for disconnection of members, and moving of members between voice channels. /// /// /// Such movements are allowed to channels that both the user to be moved and the operator have permissions to. /// - ManageVoice = 1 << 16, + ManageVoice = 1 << 16, /// /// Allows for using the everyone mention tag to notify all users in a channel, /// and the online mention tag to notify all online users in a channel. /// - MentionEveryone = 1 << 17, + MentionEveryone = 1 << 17, /// /// Allows for the addition of reactions to messages. /// - AddReactions = 1 << 18, + AddReactions = 1 << 18, /// /// Limits the user to connecting to a voice channel only when the user is invited or moved by others. /// - PassiveConnect = 1 << 20, + PassiveConnect = 1 << 20, /// /// Allows for speaking in voice a channel without having to press the speaking key. /// - UseVoiceActivity = 1 << 22, + UseVoiceActivity = 1 << 22, /// /// Allows for speaking in a voice channel. /// - Speak = 1 << 23, + Speak = 1 << 23, /// /// Allows for deafening of members in a voice channel. /// - DeafenMembers = 1 << 24, + DeafenMembers = 1 << 24, /// /// Allows for muting members in a voice channel. /// - MuteMembers = 1 << 25, + MuteMembers = 1 << 25, /// /// Allows for playing soundtracks in a voice channel. /// - PlaySoundtrack = 1 << 27, + PlaySoundtrack = 1 << 27, /// /// Allows for screen share. /// - ShareScreen = 1 << 28 -} \ No newline at end of file + ShareScreen = 1 << 28 +} diff --git a/src/Kook.Net.Core/Entities/Permissions/ChannelPermissions.cs b/src/Kook.Net.Core/Entities/Permissions/ChannelPermissions.cs index 14405066..168a932b 100644 --- a/src/Kook.Net.Core/Entities/Permissions/ChannelPermissions.cs +++ b/src/Kook.Net.Core/Entities/Permissions/ChannelPermissions.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; namespace Kook; @@ -29,10 +29,10 @@ public static ChannelPermissions All(IChannel channel) _ => throw new ArgumentException("Unknown channel type.", nameof(channel)), }; } - + /// Gets a packed value representing all the permissions in this . public ulong RawValue { get; } - + /// If true, a user may create invites. public bool CreateInvites => Permissions.GetValue(RawValue, ChannelPermission.CreateInvites); /// If true, a user may view and revoke invites. @@ -69,7 +69,7 @@ public static ChannelPermissions All(IChannel channel) public bool PlaySoundtrack => Permissions.GetValue(RawValue, ChannelPermission.PlaySoundtrack); /// If true, a user may share screen in a voice channel. public bool ShareScreen => Permissions.GetValue(RawValue, ChannelPermission.ShareScreen); - + /// Creates a new with the provided packed value. public ChannelPermissions(ulong rawValue) { RawValue = rawValue; } @@ -113,7 +113,7 @@ private ChannelPermissions(ulong initialValue, Permissions.SetValue(ref value, muteMembers, ChannelPermission.MuteMembers); Permissions.SetValue(ref value, playSoundtrack, ChannelPermission.PlaySoundtrack); Permissions.SetValue(ref value, shareScreen, ChannelPermission.ShareScreen); - + RawValue = value; } @@ -198,7 +198,7 @@ public ChannelPermissions Modify( public List ToList() { List perms = new(); - + // bitwise operations on raw value // each of the ChannelPermissions increments by 2^i from 0 to MaxBits for (byte i = 0; i < Permissions.MaxBits; i++) @@ -212,4 +212,4 @@ public List ToList() public override string ToString() => RawValue.ToString(); private string DebuggerDisplay => $"{string.Join(", ", ToList())}"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Permissions/GuildPermission.cs b/src/Kook.Net.Core/Entities/Permissions/GuildPermission.cs index 95b25bb7..f1a71b9c 100644 --- a/src/Kook.Net.Core/Entities/Permissions/GuildPermission.cs +++ b/src/Kook.Net.Core/Entities/Permissions/GuildPermission.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; [Flags] public enum GuildPermission : uint @@ -6,121 +6,121 @@ public enum GuildPermission : uint /// /// Allows all permissions and bypasses channel permission overwrites. /// - Administrator = 1 << 0, + Administrator = 1 << 0, /// /// Allows management and editing of guild. /// - ManageGuild = 1 << 1, + ManageGuild = 1 << 1, /// /// Allows for viewing of audit logs. /// - ViewAuditLog = 1 << 2, + ViewAuditLog = 1 << 2, /// /// Allows creation of invites. /// - CreateInvites = 1 << 3, + CreateInvites = 1 << 3, /// /// Allows for management of invites. /// - ManageInvites = 1 << 4, + ManageInvites = 1 << 4, /// /// Allows management and editing of channels. /// - ManageChannels = 1 << 5, + ManageChannels = 1 << 5, /// /// Allows kicking members. /// - KickMembers = 1 << 6, + KickMembers = 1 << 6, /// /// Allows banning members. /// - BanMembers = 1 << 7, + BanMembers = 1 << 7, /// /// Allows management and editing of emojis and stickers. /// - ManageEmojis = 1 << 8, + ManageEmojis = 1 << 8, /// /// Allows for modification of own nickname. /// - ChangeNickname = 1 << 9, + ChangeNickname = 1 << 9, /// /// Allows management and editing of roles. /// - ManageRoles = 1 << 10, + ManageRoles = 1 << 10, /// /// Allows guild members to view a channel, which includes reading messages in text channels. /// - ViewChannel = 1 << 11, + ViewChannel = 1 << 11, /// /// Allows for sending messages in a channel /// - SendMessages = 1 << 12, + SendMessages = 1 << 12, /// /// Allows for deletion of other users messages. /// - ManageMessages = 1 << 13, + ManageMessages = 1 << 13, /// /// Allows for uploading images and files. /// - AttachFiles = 1 << 14, + AttachFiles = 1 << 14, /// /// Allows for joining of a voice channel. /// - Connect = 1 << 15, + Connect = 1 << 15, /// /// Allows for disconnection of members, and moving of members between voice channels. /// /// /// Such movements are allowed to channels that both the user to be moved and the operator have permissions to. /// - ManageVoice = 1 << 16, + ManageVoice = 1 << 16, /// /// Allows for using the everyone mention tag to notify all users in a channel, /// and the online mention tag to notify all online users in a channel. /// - MentionEveryone = 1 << 17, + MentionEveryone = 1 << 17, /// /// Allows for the addition of reactions to messages. /// - AddReactions = 1 << 18, + AddReactions = 1 << 18, /// /// Allows for following of added reactions to messages. /// - FollowReactions = 1 << 19, + FollowReactions = 1 << 19, /// /// Limits the user to connecting to a voice channel only when the user is invited or moved by others. /// - PassiveConnect = 1 << 20, + PassiveConnect = 1 << 20, /// /// Limits the user to speaking in a voice channel only when pressing the speaking key. /// - OnlyPushToTalk = 1 << 21, + OnlyPushToTalk = 1 << 21, /// /// Allows for speaking in voice a channel without having to press the speaking key. /// - UseVoiceActivity = 1 << 22, + UseVoiceActivity = 1 << 22, /// /// Allows for speaking in a voice channel. /// - Speak = 1 << 23, + Speak = 1 << 23, /// /// Allows for deafening of members in a voice channel. /// - DeafenMembers = 1 << 24, + DeafenMembers = 1 << 24, /// /// Allows for muting members in a voice channel. /// - MuteMembers = 1 << 25, + MuteMembers = 1 << 25, /// /// Allows for modification of other users nicknames. /// - ManageNicknames = 1 << 26, + ManageNicknames = 1 << 26, /// /// Allows for playing soundtracks in a voice channel. /// - PlaySoundtrack = 1 << 27, + PlaySoundtrack = 1 << 27, /// /// Allows for screen share. /// - ShareScreen = 1 << 28 -} \ No newline at end of file + ShareScreen = 1 << 28 +} diff --git a/src/Kook.Net.Core/Entities/Permissions/GuildPermissions.cs b/src/Kook.Net.Core/Entities/Permissions/GuildPermissions.cs index 07568408..77c33c53 100644 --- a/src/Kook.Net.Core/Entities/Permissions/GuildPermissions.cs +++ b/src/Kook.Net.Core/Entities/Permissions/GuildPermissions.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; namespace Kook; @@ -71,13 +71,13 @@ public class GuildPermissions public bool PlaySoundtrack => Permissions.GetValue(RawValue, GuildPermission.PlaySoundtrack); /// If true, a user may share screen in a voice channel. public bool ShareScreen => Permissions.GetValue(RawValue, GuildPermission.ShareScreen); - + /// Creates a new with the provided packed value. public GuildPermissions(ulong rawValue) { RawValue = rawValue; } /// Creates a new with the provided packed value after converting to ulong. public GuildPermissions(string rawValue) { RawValue = ulong.Parse(rawValue); } - + private GuildPermissions(ulong initialValue, bool? administrator = null, bool? manageGuild = null, @@ -177,8 +177,8 @@ public GuildPermissions( bool playSoundtrack = false, bool shareScreen = false) : this(0, administrator, manageGuild, viewAuditLog, createInvites, manageInvites, manageChannels, kickMembers, - banMembers, manageEmojis, changeNickname, manageRoles, viewChannel, sendMessages, manageMessages, attachFiles, - connect, manageVoice, mentionEveryone, addReactions, followReactions, passiveConnect, onlyPushToTalk, + banMembers, manageEmojis, changeNickname, manageRoles, viewChannel, sendMessages, manageMessages, attachFiles, + connect, manageVoice, mentionEveryone, addReactions, followReactions, passiveConnect, onlyPushToTalk, useVoiceActivity, speak, deafenMembers, muteMembers, manageNicknames, playSoundtrack, shareScreen) { } @@ -241,9 +241,9 @@ public List ToList() // each of the GuildPermissions increments by 2^i from 0 to MaxBits for (byte i = 0; i < Permissions.MaxBits; i++) { - ulong flag = ((ulong) 1 << i); + ulong flag = ((ulong)1 << i); if ((RawValue & flag) != 0) - perms.Add((GuildPermission) flag); + perms.Add((GuildPermission)flag); } return perms; @@ -264,4 +264,4 @@ internal void Ensure(GuildPermission permissions) public override string ToString() => RawValue.ToString(); private string DebuggerDisplay => $"{string.Join(", ", ToList())}"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Permissions/IPermissionOverwrite.cs b/src/Kook.Net.Core/Entities/Permissions/IPermissionOverwrite.cs index c97c705f..8357ff5a 100644 --- a/src/Kook.Net.Core/Entities/Permissions/IPermissionOverwrite.cs +++ b/src/Kook.Net.Core/Entities/Permissions/IPermissionOverwrite.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Represents a generic permission overwrite. @@ -12,9 +12,9 @@ public interface IPermissionOverwrite /// Gets the target of this overwrite. /// TTarget Target { get; } - + /// /// Gets the overwritten permission. /// OverwritePermissions Permissions { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Permissions/OverwritePermissions.cs b/src/Kook.Net.Core/Entities/Permissions/OverwritePermissions.cs index 3d92a4b1..03545a17 100644 --- a/src/Kook.Net.Core/Entities/Permissions/OverwritePermissions.cs +++ b/src/Kook.Net.Core/Entities/Permissions/OverwritePermissions.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; namespace Kook; @@ -179,8 +179,8 @@ public OverwritePermissions Modify( PermValue? muteMembers = null, PermValue? playSoundtrack = null, PermValue? shareScreen = null) - => new OverwritePermissions(AllowValue, DenyValue, createInvites, manageChannels, manageRoles, viewChannel, - sendMessages, manageMessages, attachFiles, connect, manageVoice, mentionEveryone, addReactions, + => new OverwritePermissions(AllowValue, DenyValue, createInvites, manageChannels, manageRoles, viewChannel, + sendMessages, manageMessages, attachFiles, connect, manageVoice, mentionEveryone, addReactions, passiveConnect, useVoiceActivity, speak, deafenMembers, muteMembers, playSoundtrack, shareScreen); /// @@ -193,9 +193,9 @@ public List ToAllowList() for (byte i = 0; i < Permissions.MaxBits; i++) { // first operand must be long or ulong to shift >31 bits - ulong flag = ((ulong) 1 << i); + ulong flag = ((ulong)1 << i); if ((AllowValue & flag) != 0) - perms.Add((ChannelPermission) flag); + perms.Add((ChannelPermission)flag); } return perms; @@ -210,9 +210,9 @@ public List ToDenyList() List perms = new(); for (byte i = 0; i < Permissions.MaxBits; i++) { - ulong flag = ((ulong) 1 << i); + ulong flag = ((ulong)1 << i); if ((DenyValue & flag) != 0) - perms.Add((ChannelPermission) flag); + perms.Add((ChannelPermission)flag); } return perms; @@ -223,4 +223,4 @@ public List ToDenyList() private string DebuggerDisplay => $"Allow {string.Join(", ", ToAllowList())}, " + $"Deny {string.Join(", ", ToDenyList())}"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Permissions/PermValue.cs b/src/Kook.Net.Core/Entities/Permissions/PermValue.cs index c70a7718..6948afee 100644 --- a/src/Kook.Net.Core/Entities/Permissions/PermValue.cs +++ b/src/Kook.Net.Core/Entities/Permissions/PermValue.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// Specifies the permission value. public enum PermValue @@ -9,4 +9,4 @@ public enum PermValue Deny, /// Inherits the permission settings. Inherit -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Permissions/RolePermissionOverwrite.cs b/src/Kook.Net.Core/Entities/Permissions/RolePermissionOverwrite.cs index 29c1d3df..d1caa11e 100644 --- a/src/Kook.Net.Core/Entities/Permissions/RolePermissionOverwrite.cs +++ b/src/Kook.Net.Core/Entities/Permissions/RolePermissionOverwrite.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Represent a permission object for a role. @@ -9,12 +9,12 @@ public class RolePermissionOverwrite : IPermissionOverwrite /// Gets the identifier for the role this overwrite is targeting. /// public uint Target { get; } - + /// /// Gets the permissions associated with this overwrite entry for a role. /// public OverwritePermissions Permissions { get; } - + /// /// Initializes a new with provided ID of the role and modified permissions. /// @@ -23,4 +23,4 @@ public RolePermissionOverwrite(uint targetId, OverwritePermissions permissions) Target = targetId; Permissions = permissions; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Permissions/UserPermissionOverwrite.cs b/src/Kook.Net.Core/Entities/Permissions/UserPermissionOverwrite.cs index 1d4861cb..34737966 100644 --- a/src/Kook.Net.Core/Entities/Permissions/UserPermissionOverwrite.cs +++ b/src/Kook.Net.Core/Entities/Permissions/UserPermissionOverwrite.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; /// /// Represent a permission object for a user. @@ -9,12 +9,12 @@ public class UserPermissionOverwrite : IPermissionOverwrite /// Gets the user this overwrite is targeting. /// public IUser Target { get; } - + /// /// Gets the permissions associated with this overwrite entry for a user. /// public OverwritePermissions Permissions { get; } - + /// /// Initializes a new with provided user information and modified permissions. /// @@ -23,4 +23,4 @@ public UserPermissionOverwrite(IUser target, OverwritePermissions permissions) Target = target; Permissions = permissions; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Roles/Color.cs b/src/Kook.Net.Core/Entities/Roles/Color.cs index e7845232..203ba2b6 100644 --- a/src/Kook.Net.Core/Entities/Roles/Color.cs +++ b/src/Kook.Net.Core/Entities/Roles/Color.cs @@ -221,4 +221,4 @@ public override string ToString() => string.Format("#{0:X6}", RawValue); private string DebuggerDisplay => string.Format("#{0:X6} ({0})", RawValue); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Roles/IRole.cs b/src/Kook.Net.Core/Entities/Roles/IRole.cs index 34dffeab..01b4293a 100644 --- a/src/Kook.Net.Core/Entities/Roles/IRole.cs +++ b/src/Kook.Net.Core/Entities/Roles/IRole.cs @@ -1,4 +1,4 @@ -using System.Drawing; +using System.Drawing; namespace Kook; @@ -87,4 +87,4 @@ public interface IRole : IEntity, IDeletable, IMentionable, IComparable IAsyncEnumerable> GetUsersAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Roles/RoleProperties.cs b/src/Kook.Net.Core/Entities/Roles/RoleProperties.cs index a78b8d75..3e6a7e7f 100644 --- a/src/Kook.Net.Core/Entities/Roles/RoleProperties.cs +++ b/src/Kook.Net.Core/Entities/Roles/RoleProperties.cs @@ -38,4 +38,4 @@ public class RoleProperties /// Gets or sets the role's . /// public GuildPermissions Permissions { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/SortMode.cs b/src/Kook.Net.Core/Entities/SortMode.cs index 9d99f208..c953710f 100644 --- a/src/Kook.Net.Core/Entities/SortMode.cs +++ b/src/Kook.Net.Core/Entities/SortMode.cs @@ -13,4 +13,4 @@ public enum SortMode /// The items are sorted in descending order. /// Descending = 1 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Users/ClientType.cs b/src/Kook.Net.Core/Entities/Users/ClientType.cs index 62445cd1..614cbf52 100644 --- a/src/Kook.Net.Core/Entities/Users/ClientType.cs +++ b/src/Kook.Net.Core/Entities/Users/ClientType.cs @@ -17,4 +17,4 @@ public enum ClientType /// The user is active using the iOS application. /// iOS -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Users/IGuildUser.cs b/src/Kook.Net.Core/Entities/Users/IGuildUser.cs index 2aa12326..99e71866 100644 --- a/src/Kook.Net.Core/Entities/Users/IGuildUser.cs +++ b/src/Kook.Net.Core/Entities/Users/IGuildUser.cs @@ -96,7 +96,7 @@ public interface IGuildUser : IUser, IVoiceState /// permissions this user has in the guild. /// GuildPermissions GuildPermissions { get; } - + /// /// Gets the level permissions granted to this user to a given channel. /// @@ -152,7 +152,7 @@ public interface IGuildUser : IUser, IVoiceState #endregion #region Roles - + /// /// Adds the specified role to this user in the guild. /// @@ -225,11 +225,11 @@ public interface IGuildUser : IUser, IVoiceState /// A task that represents the asynchronous role removal operation. /// Task RemoveRolesAsync(IEnumerable roles, RequestOptions options = null); - + #endregion #region Voice - + /// /// Mute this user in this guild. /// @@ -238,7 +238,7 @@ public interface IGuildUser : IUser, IVoiceState /// A task that represents the asynchronous muting operation. /// Task MuteAsync(RequestOptions options = null); - + /// /// Deafen this user in this guild. /// @@ -247,7 +247,7 @@ public interface IGuildUser : IUser, IVoiceState /// A task that represents the asynchronous deafening operation. /// Task DeafenAsync(RequestOptions options = null); - + /// /// Unmute this user in this guild. /// @@ -256,7 +256,7 @@ public interface IGuildUser : IUser, IVoiceState /// A task that represents the asynchronous unmuting operation. /// Task UnmuteAsync(RequestOptions options = null); - + /// /// Undeafen this user in this guild. /// @@ -265,7 +265,7 @@ public interface IGuildUser : IUser, IVoiceState /// A task that represents the asynchronous undeafening operation. /// Task UndeafenAsync(RequestOptions options = null); - + /// /// Gets a collection of voice channels a user /// @@ -275,6 +275,6 @@ public interface IGuildUser : IUser, IVoiceState /// voice channels the user is connected to. /// Task> GetConnectedVoiceChannelsAsync(RequestOptions options = null); - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Users/IPresence.cs b/src/Kook.Net.Core/Entities/Users/IPresence.cs index b6f61837..ad7d2b43 100644 --- a/src/Kook.Net.Core/Entities/Users/IPresence.cs +++ b/src/Kook.Net.Core/Entities/Users/IPresence.cs @@ -15,4 +15,4 @@ public interface IPresence /// Gets the type of the client where this user is currently active. /// ClientType? ActiveClient { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Users/ISelfUser.cs b/src/Kook.Net.Core/Entities/Users/ISelfUser.cs index d6e9f07e..c69f08d8 100644 --- a/src/Kook.Net.Core/Entities/Users/ISelfUser.cs +++ b/src/Kook.Net.Core/Entities/Users/ISelfUser.cs @@ -51,4 +51,4 @@ public interface ISelfUser : IUser /// A task that represents the asynchronous operation for stopping an activity. /// Task StopPlayingAsync(ActivityType type, RequestOptions options = null); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Users/IUser.cs b/src/Kook.Net.Core/Entities/Users/IUser.cs index 260fc800..c62ea14a 100644 --- a/src/Kook.Net.Core/Entities/Users/IUser.cs +++ b/src/Kook.Net.Core/Entities/Users/IUser.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; public interface IUser : IEntity, IMentionable, IPresence { @@ -66,7 +66,7 @@ public interface IUser : IEntity, IMentionable, IPresence /// contains the DM channel associated with this user. /// Task CreateDMChannelAsync(RequestOptions options = null); - + /// /// Gets the intimacy information with this user. /// @@ -76,7 +76,7 @@ public interface IUser : IEntity, IMentionable, IPresence /// contains the intimacy information associated with this user. /// Task GetIntimacyAsync(RequestOptions options = null); - + /// /// Updates the intimacy information with this user. /// @@ -84,4 +84,4 @@ public interface IUser : IEntity, IMentionable, IPresence /// The options to be used when sending the request. /// A task that represents the asynchronous operation for updating the intimacy information. Task UpdateIntimacyAsync(Action func, RequestOptions options); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Users/IVoiceState.cs b/src/Kook.Net.Core/Entities/Users/IVoiceState.cs index 34a841d6..f8538338 100644 --- a/src/Kook.Net.Core/Entities/Users/IVoiceState.cs +++ b/src/Kook.Net.Core/Entities/Users/IVoiceState.cs @@ -31,4 +31,4 @@ public interface IVoiceState /// if none. /// IVoiceChannel VoiceChannel { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Users/SearchGuildMemberProperties.cs b/src/Kook.Net.Core/Entities/Users/SearchGuildMemberProperties.cs index 5144ba38..6f6da2e4 100644 --- a/src/Kook.Net.Core/Entities/Users/SearchGuildMemberProperties.cs +++ b/src/Kook.Net.Core/Entities/Users/SearchGuildMemberProperties.cs @@ -31,4 +31,4 @@ public class SearchGuildMemberProperties /// null to not sort by joining time. /// public SortMode? SortedByJoinTime { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Entities/Users/UserTag.cs b/src/Kook.Net.Core/Entities/Users/UserTag.cs index 81bb9fe9..df298ce7 100644 --- a/src/Kook.Net.Core/Entities/Users/UserTag.cs +++ b/src/Kook.Net.Core/Entities/Users/UserTag.cs @@ -50,18 +50,23 @@ private UserTag(Color color, string text) /// public bool Equals(UserTag other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + return false; + if (ReferenceEquals(this, other)) + return true; return Text == other.Text; } /// public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; - return Equals((UserTag) obj); + if (ReferenceEquals(null, obj)) + return false; + if (ReferenceEquals(this, obj)) + return true; + if (obj.GetType() != this.GetType()) + return false; + return Equals((UserTag)obj); } /// @@ -69,7 +74,7 @@ public override int GetHashCode() { return (Text != null ? Text.GetHashCode() : 0); } - + #endregion - -} \ No newline at end of file + +} diff --git a/src/Kook.Net.Core/Extensions/AsyncEnumerableExtensions.cs b/src/Kook.Net.Core/Extensions/AsyncEnumerableExtensions.cs index 8c0b83ff..c611901f 100644 --- a/src/Kook.Net.Core/Extensions/AsyncEnumerableExtensions.cs +++ b/src/Kook.Net.Core/Extensions/AsyncEnumerableExtensions.cs @@ -18,4 +18,4 @@ public static IAsyncEnumerable Flatten(this IAsyncEnumerable enumerable.ToAsyncEnumerable()); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Extensions/ChannelExtensions.cs b/src/Kook.Net.Core/Extensions/ChannelExtensions.cs index 6090e277..3e5f252a 100644 --- a/src/Kook.Net.Core/Extensions/ChannelExtensions.cs +++ b/src/Kook.Net.Core/Extensions/ChannelExtensions.cs @@ -18,7 +18,7 @@ public static class ChannelExtensions _ => null }; } - + /// /// Gets a URL that jumps to the channel. /// @@ -35,4 +35,4 @@ public static string GetJumpUrl(this IChannel channel) _ => throw new ArgumentException("Channel must be a guild or a DM channel.", nameof(channel)) }; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Extensions/CollectionExtensions.cs b/src/Kook.Net.Core/Extensions/CollectionExtensions.cs index fbc815e9..ebf6a1c8 100644 --- a/src/Kook.Net.Core/Extensions/CollectionExtensions.cs +++ b/src/Kook.Net.Core/Extensions/CollectionExtensions.cs @@ -38,4 +38,4 @@ public CollectionWrapper(IEnumerable query, Func countFunc) public IEnumerator GetEnumerator() => _query.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _query.GetEnumerator(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Extensions/MessageExtensions.cs b/src/Kook.Net.Core/Extensions/MessageExtensions.cs index f2ec9688..0be66008 100644 --- a/src/Kook.Net.Core/Extensions/MessageExtensions.cs +++ b/src/Kook.Net.Core/Extensions/MessageExtensions.cs @@ -87,8 +87,8 @@ public static async Task RemoveReactionsAsync(this IUserMessage msg, IUser user, /// true if the source message will be quoted in this message; otherwise, false. /// true if the message to be sent can be seen only by the command invoker; otherwise, false. /// The options to be used when sending the request. - public static async Task> ReplyFileAsync(this IUserMessage message, - string path, string fileName = null, AttachmentType type = AttachmentType.File, bool isQuote = false, bool isEphemeral = false, + public static async Task> ReplyFileAsync(this IUserMessage message, + string path, string fileName = null, AttachmentType type = AttachmentType.File, bool isQuote = false, bool isEphemeral = false, RequestOptions options = null) { return await message.Channel.SendFileAsync(path, fileName, type, isQuote ? new Quote(message.Id) : null, @@ -104,8 +104,8 @@ public static async Task> ReplyFileAsync(this IUse /// true if the source message will be quoted in this message; otherwise, false. /// true if the message to be sent can be seen only by the command invoker; otherwise, false. /// The options to be used when sending the request. - public static async Task> ReplyFileAsync(this IUserMessage message, - Stream stream, string fileName = null, AttachmentType type = AttachmentType.File, bool isQuote = false, bool isEphemeral = false, + public static async Task> ReplyFileAsync(this IUserMessage message, + Stream stream, string fileName = null, AttachmentType type = AttachmentType.File, bool isQuote = false, bool isEphemeral = false, RequestOptions options = null) { return await message.Channel.SendFileAsync(stream, fileName, type, isQuote ? new Quote(message.Id) : null, @@ -119,7 +119,7 @@ public static async Task> ReplyFileAsync(this IUse /// true if the source message will be quoted in this message; otherwise, false. /// true if the message to be sent can be seen only by the command invoker; otherwise, false. /// The options to be used when sending the request. - public static async Task> ReplyFileAsync(this IUserMessage message, + public static async Task> ReplyFileAsync(this IUserMessage message, FileAttachment attachment, bool isQuote = false, bool isEphemeral = false, RequestOptions options = null) { return await message.Channel.SendFileAsync(attachment, isQuote ? new Quote(message.Id) : null, @@ -133,7 +133,7 @@ public static async Task> ReplyFileAsync(this IUse /// true if the source message will be quoted in this message; otherwise, false. /// true if the message to be sent can be seen only by the command invoker; otherwise, false. /// The request options for this request. - public static async Task> ReplyTextAsync(this IUserMessage message, + public static async Task> ReplyTextAsync(this IUserMessage message, string content, bool isQuote = false, bool isEphemeral = false, RequestOptions options = null) { return await message.Channel.SendTextAsync(content, isQuote ? new Quote(message.Id) : null, @@ -147,7 +147,7 @@ public static async Task> ReplyTextAsync(this IUse /// true if the source message will be quoted in this message; otherwise, false. /// true if the message to be sent can be seen only by the command invoker; otherwise, false. /// The request options for this request. - public static async Task> ReplyCardsAsync(this IUserMessage message, + public static async Task> ReplyCardsAsync(this IUserMessage message, IEnumerable cards, bool isQuote = false, bool isEphemeral = false, RequestOptions options = null) { return await message.Channel.SendCardsAsync(cards, isQuote ? new Quote(message.Id) : null, @@ -169,5 +169,5 @@ public static async Task> ReplyCardAsync( return await message.Channel.SendCardAsync(card, isQuote ? new Quote(message.Id) : null, isEphemeral ? message.Author : null, options).ConfigureAwait(false); } - -} \ No newline at end of file + +} diff --git a/src/Kook.Net.Core/Extensions/TaskCompletionSourceExtensions.cs b/src/Kook.Net.Core/Extensions/TaskCompletionSourceExtensions.cs index 1c18bd97..decc63c6 100644 --- a/src/Kook.Net.Core/Extensions/TaskCompletionSourceExtensions.cs +++ b/src/Kook.Net.Core/Extensions/TaskCompletionSourceExtensions.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; internal static class TaskCompletionSourceExtensions { @@ -16,4 +16,4 @@ public static Task SetCanceledAsync(this TaskCompletionSource source) => Task.Run(() => source.SetCanceled()); public static Task TrySetCanceledAsync(this TaskCompletionSource source) => Task.Run(() => source.TrySetCanceled()); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Extensions/UserExtensions.cs b/src/Kook.Net.Core/Extensions/UserExtensions.cs index ba4e770e..5ffa0d9a 100644 --- a/src/Kook.Net.Core/Extensions/UserExtensions.cs +++ b/src/Kook.Net.Core/Extensions/UserExtensions.cs @@ -1,6 +1,6 @@ using System; -using System.Threading.Tasks; using System.IO; +using System.Threading.Tasks; namespace Kook; @@ -71,7 +71,7 @@ public static async Task> SendTextAsync(this IUser /// The cards to be sent. /// The message quote to be included. Used to reply to specific messages. /// The request options for this request. - public static async Task> SendCardsAsync(this IUser user, + public static async Task> SendCardsAsync(this IUser user, IEnumerable cards, IQuote quote = null, RequestOptions options = null) { return await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendCardsAsync(cards, quote, options).ConfigureAwait(false); @@ -103,4 +103,4 @@ public static async Task> SendCardAsync(this IUser /// public static Task BanAsync(this IGuildUser user, int pruneDays = 0, string reason = null, RequestOptions options = null) => user.Guild.AddBanAsync(user, pruneDays, reason, options); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Format.cs b/src/Kook.Net.Core/Format.cs index 52f39d9a..ff0a04ef 100644 --- a/src/Kook.Net.Core/Format.cs +++ b/src/Kook.Net.Core/Format.cs @@ -37,7 +37,8 @@ public static string Colorize(string text, TextTheme theme) => /// Sanitizes the string, safely escaping any Markdown sequences. public static string Sanitize(string text) { - if (text is null) return null; + if (text is null) + return null; return SensitiveCharacters.Aggregate(text, (current, unsafeChar) => current.Replace(unsafeChar, $"\\{unsafeChar}")); } @@ -137,4 +138,4 @@ public static string UsernameAndIdentifyNumber(IUser user) { return $"\u2066{user.Username}\u2069#{user.IdentifyNumber}"; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/IKookClient.cs b/src/Kook.Net.Core/IKookClient.cs index e5305f44..31a2fcb9 100644 --- a/src/Kook.Net.Core/IKookClient.cs +++ b/src/Kook.Net.Core/IKookClient.cs @@ -41,11 +41,11 @@ public interface IKookClient : IDisposable /// A task that represents the asynchronous stop operation. /// Task StopAsync(); - + #endregion #region Channels - + /// /// Gets a generic channel. /// @@ -87,9 +87,9 @@ public interface IKookClient : IDisposable Task> GetDMChannelsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); #endregion - + #region Guilds - + /// /// Gets a guild. /// @@ -111,11 +111,11 @@ public interface IKookClient : IDisposable /// of guilds that the current user is in. /// Task> GetGuildsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); - + #endregion - + #region Users - + /// /// Gets a user. /// @@ -127,7 +127,7 @@ public interface IKookClient : IDisposable /// the identifier; null if the user is not found. /// Task GetUserAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null); - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/KookConfig.cs b/src/Kook.Net.Core/KookConfig.cs index 12778a91..8bb48cfc 100644 --- a/src/Kook.Net.Core/KookConfig.cs +++ b/src/Kook.Net.Core/KookConfig.cs @@ -17,7 +17,7 @@ public class KookConfig /// . /// public const int APIVersion = 3; - + /// /// Gets the Kook.Net version, including the build number. /// @@ -26,8 +26,8 @@ public class KookConfig /// the version fails to be fetched. /// public static string Version { get; } = - typeof(KookConfig).GetTypeInfo().Assembly.GetCustomAttribute()?.InformationalVersion - ?? typeof(KookConfig).GetTypeInfo().Assembly.GetName().Version?.ToString(3) + typeof(KookConfig).GetTypeInfo().Assembly.GetCustomAttribute()?.InformationalVersion + ?? typeof(KookConfig).GetTypeInfo().Assembly.GetName().Version?.ToString(3) ?? "Unknown"; /// @@ -59,7 +59,7 @@ public class KookConfig /// The amount of time it takes in milliseconds before a request is timed out. /// public const int DefaultRequestTimeout = 6000; - + /// /// Returns the max length for a Kook message. /// @@ -73,7 +73,7 @@ public class KookConfig /// /// public const int MaxMessageSize = 20000; - + /// /// Returns the max users allowed to be in a request. /// @@ -81,7 +81,7 @@ public class KookConfig /// The maximum number of users that can be gotten per-batch. /// public const int MaxUsersPerBatch = 50; - + /// /// Returns the max messages allowed to be in a request. /// @@ -89,7 +89,7 @@ public class KookConfig /// The maximum number of messages that can be gotten per-batch. /// public const int MaxMessagesPerBatch = 100; - + /// /// Returns the max items allowed to be in a request by default. /// @@ -97,7 +97,7 @@ public class KookConfig /// The maximum number of items that can be gotten per-batch by default. /// public const int MaxItemsPerBatchByDefault = 100; - + /// /// Returns the min length for a Kook guild nickname. /// @@ -105,7 +105,7 @@ public class KookConfig /// The minimum length of a nickname allowed by Kook. /// public const int MinNicknameSize = 2; - + /// /// Returns the max length for a Kook guild nickname. /// @@ -121,7 +121,7 @@ public class KookConfig /// The minimum value of an intimacy score allowed by Kook. /// public const int MinIntimacyScore = 0; - + /// /// Returns the max value for a Kook intimacy score. /// @@ -172,4 +172,4 @@ public class KookConfig /// Gets the user identifier of the author who sends system messages from Kook official. /// internal const ulong SystemMessageAuthorID = 3900775823; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/KookErrorCode.cs b/src/Kook.Net.Core/KookErrorCode.cs index 79e0bf13..9712f89a 100644 --- a/src/Kook.Net.Core/KookErrorCode.cs +++ b/src/Kook.Net.Core/KookErrorCode.cs @@ -18,7 +18,7 @@ public enum KookErrorCode #endregion RequestEntityTooLarge = 40014, - + #region Reconnect MissingResumeArgument = 40106, @@ -26,6 +26,6 @@ public enum KookErrorCode InvalidSequenceNumber = 40108, #endregion - + MissingPermissions = 40300 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/KookJsonError.cs b/src/Kook.Net.Core/KookJsonError.cs index d414ec2d..add5bf18 100644 --- a/src/Kook.Net.Core/KookJsonError.cs +++ b/src/Kook.Net.Core/KookJsonError.cs @@ -44,4 +44,4 @@ internal KookError(string code, string message) Code = code; Message = message; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Logging/LogManager.cs b/src/Kook.Net.Core/Logging/LogManager.cs index 61049a5d..d1354fca 100644 --- a/src/Kook.Net.Core/Logging/LogManager.cs +++ b/src/Kook.Net.Core/Logging/LogManager.cs @@ -107,4 +107,4 @@ public async Task WriteInitialLog() { await ClientLogger.InfoAsync($"Kook.Net v{KookConfig.Version} (API v{KookConfig.APIVersion})").ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Logging/LogMessage.cs b/src/Kook.Net.Core/Logging/LogMessage.cs index 00e27018..4850aa81 100644 --- a/src/Kook.Net.Core/Logging/LogMessage.cs +++ b/src/Kook.Net.Core/Logging/LogMessage.cs @@ -52,7 +52,7 @@ public LogMessage(LogSeverity severity, string source, string message, Exception Message = message; Exception = exception; } - + public override string ToString() => ToString(); public string ToString(StringBuilder builder = null, bool fullException = true, bool prependTimestamp = true, DateTimeKind timestampKind = DateTimeKind.Local, int? padSource = 11) { @@ -60,9 +60,9 @@ public string ToString(StringBuilder builder = null, bool fullException = true, string message = Message; string exMessage = fullException ? Exception?.ToString() : Exception?.Message; - int maxLength = 1 + + int maxLength = 1 + (prependTimestamp ? 8 : 0) + 1 + - (padSource ?? (sourceName?.Length ?? 0)) + 1 + + (padSource ?? (sourceName?.Length ?? 0)) + 1 + (message?.Length ?? 0) + (exMessage?.Length ?? 0) + 3; diff --git a/src/Kook.Net.Core/Logging/LogSeverity.cs b/src/Kook.Net.Core/Logging/LogSeverity.cs index d8ed016b..60ef7bf1 100644 --- a/src/Kook.Net.Core/Logging/LogSeverity.cs +++ b/src/Kook.Net.Core/Logging/LogSeverity.cs @@ -30,4 +30,4 @@ public enum LogSeverity /// Logs that contain the most detailed messages. /// Debug = 5 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Logging/Logger.cs b/src/Kook.Net.Core/Logging/Logger.cs index fcb03e34..f3395c1e 100644 --- a/src/Kook.Net.Core/Logging/Logger.cs +++ b/src/Kook.Net.Core/Logging/Logger.cs @@ -68,4 +68,4 @@ public Task DebugAsync(string message, Exception exception = null) public Task DebugAsync(FormattableString message, Exception exception = null) => _manager.DebugAsync(Name, message, exception); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/LoginState.cs b/src/Kook.Net.Core/LoginState.cs index 74802c95..44d761de 100644 --- a/src/Kook.Net.Core/LoginState.cs +++ b/src/Kook.Net.Core/LoginState.cs @@ -11,4 +11,4 @@ public enum LoginState : byte LoggedIn, /// The client is currently logging out. LoggingOut -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Net/BucketId.cs b/src/Kook.Net.Core/Net/BucketId.cs index 9d0bb7e0..dec3a495 100644 --- a/src/Kook.Net.Core/Net/BucketId.cs +++ b/src/Kook.Net.Core/Net/BucketId.cs @@ -94,7 +94,7 @@ public override bool Equals(object obj) => Equals(obj as BucketId); public override int GetHashCode() - => IsHashBucket ? (BucketHash, string.Join("/", MajorParameters.Select(x => x.Value))).GetHashCode() : (HttpMethod, Endpoint).GetHashCode(); + => IsHashBucket ? (BucketHash, string.Join("/", MajorParameters.Select(x => x.Value))).GetHashCode() : (HttpMethod, Endpoint).GetHashCode(); public override string ToString() => GetBucketHash() ?? GetUniqueEndpoint(); @@ -108,5 +108,5 @@ public bool Equals(BucketId other) if (GetType() != other.GetType()) return false; return ToString() == other.ToString(); - } -} \ No newline at end of file + } +} diff --git a/src/Kook.Net.Core/Net/HttpException.cs b/src/Kook.Net.Core/Net/HttpException.cs index 15f57b9d..8e2f295c 100644 --- a/src/Kook.Net.Core/Net/HttpException.cs +++ b/src/Kook.Net.Core/Net/HttpException.cs @@ -53,7 +53,7 @@ public HttpException(HttpStatusCode httpCode, IRequest request, KookErrorCode? k } private static string CreateMessage(HttpStatusCode httpCode, int? kookCode = null, string reason = null) - { + { string msg; if (kookCode != null && kookCode != 0) { @@ -71,4 +71,4 @@ private static string CreateMessage(HttpStatusCode httpCode, int? kookCode = nul } return msg; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Net/IRequest.cs b/src/Kook.Net.Core/Net/IRequest.cs index beac9701..85696b5e 100644 --- a/src/Kook.Net.Core/Net/IRequest.cs +++ b/src/Kook.Net.Core/Net/IRequest.cs @@ -7,4 +7,4 @@ public interface IRequest { DateTimeOffset? TimeoutAt { get; } RequestOptions Options { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Net/RateLimitedException.cs b/src/Kook.Net.Core/Net/RateLimitedException.cs index cdc6cb48..b9ccdf24 100644 --- a/src/Kook.Net.Core/Net/RateLimitedException.cs +++ b/src/Kook.Net.Core/Net/RateLimitedException.cs @@ -19,4 +19,4 @@ public RateLimitedException(IRequest request) { Request = request; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Net/Rest/IRateLimitInfo.cs b/src/Kook.Net.Core/Net/Rest/IRateLimitInfo.cs index e5e6c7cc..80c51dbb 100644 --- a/src/Kook.Net.Core/Net/Rest/IRateLimitInfo.cs +++ b/src/Kook.Net.Core/Net/Rest/IRateLimitInfo.cs @@ -49,4 +49,4 @@ public interface IRateLimitInfo /// Gets the endpoint that this ratelimit info came from. /// string Endpoint { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Net/Rest/IRestClient.cs b/src/Kook.Net.Core/Net/Rest/IRestClient.cs index 2c17d72d..2c499ef5 100644 --- a/src/Kook.Net.Core/Net/Rest/IRestClient.cs +++ b/src/Kook.Net.Core/Net/Rest/IRestClient.cs @@ -32,4 +32,4 @@ Task SendAsync(HttpMethod method, string endpoint, string json, Ca IEnumerable>> requestHeaders = null); Task SendAsync(HttpMethod method, string endpoint, IReadOnlyDictionary multipartParams, CancellationToken cancelToken, string reason = null, IEnumerable>> requestHeaders = null); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Net/Rest/RestClientProvider.cs b/src/Kook.Net.Core/Net/Rest/RestClientProvider.cs index a91207ee..4229f626 100644 --- a/src/Kook.Net.Core/Net/Rest/RestClientProvider.cs +++ b/src/Kook.Net.Core/Net/Rest/RestClientProvider.cs @@ -1,3 +1,3 @@ -namespace Kook.Net.Rest; +namespace Kook.Net.Rest; -public delegate IRestClient RestClientProvider(string baseUrl); \ No newline at end of file +public delegate IRestClient RestClientProvider(string baseUrl); diff --git a/src/Kook.Net.Core/Net/Rest/RestResponse.cs b/src/Kook.Net.Core/Net/Rest/RestResponse.cs index ee32587a..6b754047 100644 --- a/src/Kook.Net.Core/Net/Rest/RestResponse.cs +++ b/src/Kook.Net.Core/Net/Rest/RestResponse.cs @@ -1,4 +1,4 @@ -using System.Net; +using System.Net; using System.Net.Http.Headers; namespace Kook.Net.Rest; @@ -8,7 +8,7 @@ public struct RestResponse public HttpStatusCode StatusCode { get; } public Dictionary Headers { get; } public Stream Stream { get; } - + public MediaTypeHeaderValue MediaTypeHeader { get; } public RestResponse(HttpStatusCode statusCode, Dictionary headers, Stream stream, MediaTypeHeaderValue mediaTypeHeader) @@ -18,4 +18,4 @@ public RestResponse(HttpStatusCode statusCode, Dictionary header Stream = stream; MediaTypeHeader = mediaTypeHeader; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Net/Udp/IUdpSocket.cs b/src/Kook.Net.Core/Net/Udp/IUdpSocket.cs index 6a7de81b..9829b963 100644 --- a/src/Kook.Net.Core/Net/Udp/IUdpSocket.cs +++ b/src/Kook.Net.Core/Net/Udp/IUdpSocket.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading; using System.Threading.Tasks; @@ -17,4 +17,4 @@ public interface IUdpSocket : IDisposable Task StopAsync(); Task SendAsync(byte[] data, int index, int count); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Net/Udp/UdpSocketProvider.cs b/src/Kook.Net.Core/Net/Udp/UdpSocketProvider.cs index 5bb1f5b1..b231bcd8 100644 --- a/src/Kook.Net.Core/Net/Udp/UdpSocketProvider.cs +++ b/src/Kook.Net.Core/Net/Udp/UdpSocketProvider.cs @@ -1,3 +1,3 @@ -namespace Kook.Net.Udp; +namespace Kook.Net.Udp; -public delegate IUdpSocket UdpSocketProvider(); \ No newline at end of file +public delegate IUdpSocket UdpSocketProvider(); diff --git a/src/Kook.Net.Core/Net/WebSocketClosedException.cs b/src/Kook.Net.Core/Net/WebSocketClosedException.cs index e33c3b98..0c17f8fd 100644 --- a/src/Kook.Net.Core/Net/WebSocketClosedException.cs +++ b/src/Kook.Net.Core/Net/WebSocketClosedException.cs @@ -29,4 +29,4 @@ public WebSocketClosedException(int closeCode, string reason = null) CloseCode = closeCode; Reason = reason; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Net/WebSockets/IWebSocketClient.cs b/src/Kook.Net.Core/Net/WebSockets/IWebSocketClient.cs index 1dbce368..7b431a1e 100644 --- a/src/Kook.Net.Core/Net/WebSockets/IWebSocketClient.cs +++ b/src/Kook.Net.Core/Net/WebSockets/IWebSocketClient.cs @@ -1,4 +1,4 @@ -namespace Kook.Net.WebSockets; +namespace Kook.Net.WebSockets; /// /// Represents a generic WebSocket client. @@ -16,4 +16,4 @@ public interface IWebSocketClient : IDisposable Task DisconnectAsync(int closeCode = 1000); Task SendAsync(byte[] data, int index, int count, bool isText); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Net/WebSockets/WebSocketProvider.cs b/src/Kook.Net.Core/Net/WebSockets/WebSocketProvider.cs index e5bc7e2d..04bcfdc3 100644 --- a/src/Kook.Net.Core/Net/WebSockets/WebSocketProvider.cs +++ b/src/Kook.Net.Core/Net/WebSockets/WebSocketProvider.cs @@ -1,3 +1,3 @@ -namespace Kook.Net.WebSockets; +namespace Kook.Net.WebSockets; -public delegate IWebSocketClient WebSocketProvider(); \ No newline at end of file +public delegate IWebSocketClient WebSocketProvider(); diff --git a/src/Kook.Net.Core/RequestOptions.cs b/src/Kook.Net.Core/RequestOptions.cs index 140b3450..4657e896 100644 --- a/src/Kook.Net.Core/RequestOptions.cs +++ b/src/Kook.Net.Core/RequestOptions.cs @@ -55,11 +55,11 @@ public class RequestOptions internal BucketId BucketId { get; set; } internal bool IsClientBucket { get; set; } internal bool IsGatewayBucket { get; set; } - + internal IDictionary> RequestHeaders { get; } - + internal static RequestOptions CreateOrClone(RequestOptions options) - { + { if (options == null) return new RequestOptions(); else @@ -86,6 +86,6 @@ public RequestOptions() Timeout = KookConfig.DefaultRequestTimeout; RequestHeaders = new Dictionary>(); } - + public RequestOptions Clone() => MemberwiseClone() as RequestOptions; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/RetryMode.cs b/src/Kook.Net.Core/RetryMode.cs index bb31ce0b..009f8798 100644 --- a/src/Kook.Net.Core/RetryMode.cs +++ b/src/Kook.Net.Core/RetryMode.cs @@ -16,4 +16,4 @@ public enum RetryMode Retry502 = 0x8, /// Continuously retry a request until it times out, its cancel token is triggered, or the server responds with a non-502 error. AlwaysRetry = RetryTimeouts | /*RetryErrors |*/ RetryRatelimit | Retry502, -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/TokenType.cs b/src/Kook.Net.Core/TokenType.cs index 214cbd58..978e8df7 100644 --- a/src/Kook.Net.Core/TokenType.cs +++ b/src/Kook.Net.Core/TokenType.cs @@ -13,4 +13,4 @@ public enum TokenType /// A bot token type. /// Bot -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Utils/AsyncEvent.cs b/src/Kook.Net.Core/Utils/AsyncEvent.cs index 94a57ff9..2ce6d757 100644 --- a/src/Kook.Net.Core/Utils/AsyncEvent.cs +++ b/src/Kook.Net.Core/Utils/AsyncEvent.cs @@ -34,7 +34,7 @@ public void Remove(T subscriber) } internal static class EventExtensions -{ +{ public static async Task InvokeAsync(this AsyncEvent> eventHandler) { var subscribers = eventHandler.Subscriptions; @@ -71,4 +71,4 @@ public static async Task InvokeAsync(this AsyncEvent public TEntity Value { get; } private Func> DownloadFunc { get; } - internal Cacheable(TEntity value, TId id, bool hasValue , Func> downloadFunc) + internal Cacheable(TEntity value, TId id, bool hasValue, Func> downloadFunc) { Value = value; Id = id; @@ -118,4 +118,4 @@ public async Task DownloadAsync() /// download the entity. The task result contains the downloaded entity. /// public async Task GetOrDownloadAsync() => HasValue ? Value : await DownloadAsync().ConfigureAwait(false); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Utils/ConcurrentHashSet.cs b/src/Kook.Net.Core/Utils/ConcurrentHashSet.cs index ee68584f..112bbbb6 100644 --- a/src/Kook.Net.Core/Utils/ConcurrentHashSet.cs +++ b/src/Kook.Net.Core/Utils/ConcurrentHashSet.cs @@ -76,9 +76,9 @@ private static void GetBucketAndLockNo(int hashcode, out int bucketNo, out int l private static int DefaultConcurrencyLevel => ConcurrentHashSet.DefaultConcurrencyLevel; private volatile Tables _tables; - private readonly IEqualityComparer _comparer; + private readonly IEqualityComparer _comparer; private readonly bool _growLockArray; - private int _budget; + private int _budget; public int Count { @@ -146,19 +146,20 @@ public ReadOnlyCollection Values } } - public ConcurrentHashSet() + public ConcurrentHashSet() : this(DefaultConcurrencyLevel, DefaultCapacity, true, EqualityComparer.Default) { } - public ConcurrentHashSet(int concurrencyLevel, int capacity) + public ConcurrentHashSet(int concurrencyLevel, int capacity) : this(concurrencyLevel, capacity, false, EqualityComparer.Default) { } - public ConcurrentHashSet(IEnumerable collection) + public ConcurrentHashSet(IEnumerable collection) : this(collection, EqualityComparer.Default) { } - public ConcurrentHashSet(IEqualityComparer comparer) + public ConcurrentHashSet(IEqualityComparer comparer) : this(DefaultConcurrencyLevel, DefaultCapacity, true, comparer) { } /// is null - public ConcurrentHashSet(IEnumerable collection, IEqualityComparer comparer) + public ConcurrentHashSet(IEnumerable collection, IEqualityComparer comparer) : this(comparer) { - if (collection == null) throw new ArgumentNullException(paramName: nameof(collection)); + if (collection == null) + throw new ArgumentNullException(paramName: nameof(collection)); InitializeFromCollection(collection); } /// @@ -167,18 +168,23 @@ public ConcurrentHashSet(IEnumerable collection, IEqualityComparer compare public ConcurrentHashSet(int concurrencyLevel, IEnumerable collection, IEqualityComparer comparer) : this(concurrencyLevel, DefaultCapacity, false, comparer) { - if (collection == null) throw new ArgumentNullException(paramName: nameof(collection)); - if (comparer == null) throw new ArgumentNullException(paramName: nameof(comparer)); + if (collection == null) + throw new ArgumentNullException(paramName: nameof(collection)); + if (comparer == null) + throw new ArgumentNullException(paramName: nameof(comparer)); InitializeFromCollection(collection); - } + } public ConcurrentHashSet(int concurrencyLevel, int capacity, IEqualityComparer comparer) : this(concurrencyLevel, capacity, false, comparer) { } internal ConcurrentHashSet(int concurrencyLevel, int capacity, bool growLockArray, IEqualityComparer comparer) { - if (concurrencyLevel < 1) throw new ArgumentOutOfRangeException(paramName: nameof(concurrencyLevel)); - if (capacity < 0) throw new ArgumentOutOfRangeException(paramName: nameof(capacity)); - if (comparer == null) throw new ArgumentNullException(paramName: nameof(comparer)); - + if (concurrencyLevel < 1) + throw new ArgumentOutOfRangeException(paramName: nameof(concurrencyLevel)); + if (capacity < 0) + throw new ArgumentOutOfRangeException(paramName: nameof(capacity)); + if (comparer == null) + throw new ArgumentNullException(paramName: nameof(comparer)); + if (capacity < concurrencyLevel) capacity = concurrencyLevel; @@ -198,7 +204,8 @@ private void InitializeFromCollection(IEnumerable collection) { foreach (var value in collection) { - if (value == null) throw new ArgumentNullException(paramName: "key"); + if (value == null) + throw new ArgumentNullException(paramName: "key"); if (!TryAddInternal(value, _comparer.GetHashCode(value), false)) throw new ArgumentException(); @@ -210,7 +217,8 @@ private void InitializeFromCollection(IEnumerable collection) /// is null public bool ContainsKey(T value) { - if (value == null) throw new ArgumentNullException(paramName: "key"); + if (value == null) + throw new ArgumentNullException(paramName: "key"); return ContainsKeyInternal(value, _comparer.GetHashCode(value)); } private bool ContainsKeyInternal(T value, int hashcode) @@ -218,7 +226,7 @@ private bool ContainsKeyInternal(T value, int hashcode) Tables tables = _tables; int bucketNo = GetBucket(hashcode, tables._buckets.Length); - + Node n = Volatile.Read(ref tables._buckets[bucketNo]); while (n != null) @@ -227,14 +235,15 @@ private bool ContainsKeyInternal(T value, int hashcode) return true; n = n._next; } - + return false; } /// is null public bool TryAdd(T value) { - if (value == null) throw new ArgumentNullException(paramName: "key"); + if (value == null) + throw new ArgumentNullException(paramName: "key"); return TryAddInternal(value, _comparer.GetHashCode(value), true); } private bool TryAddInternal(T value, int hashcode, bool acquireLock) @@ -263,7 +272,8 @@ private bool TryAddInternal(T value, int hashcode, bool acquireLock) } Volatile.Write(ref tables._buckets[bucketNo], new Node(value, hashcode, tables._buckets[bucketNo])); - checked { tables._countPerLock[lockNo]++; } + checked + { tables._countPerLock[lockNo]++; } if (tables._countPerLock[lockNo] > _budget) resizeDesired = true; @@ -276,7 +286,7 @@ private bool TryAddInternal(T value, int hashcode, bool acquireLock) if (resizeDesired) GrowTable(tables); - + return true; } } @@ -284,9 +294,10 @@ private bool TryAddInternal(T value, int hashcode, bool acquireLock) /// is null public bool TryRemove(T value) { - if (value == null) throw new ArgumentNullException(paramName: "key"); + if (value == null) + throw new ArgumentNullException(paramName: "key"); return TryRemoveInternal(value); - } + } private bool TryRemoveInternal(T value) { int hashcode = _comparer.GetHashCode(value); @@ -322,7 +333,7 @@ private bool TryRemoveInternal(T value) return false; } } - + public void Clear() { int locksAcquired = 0; @@ -339,7 +350,7 @@ public void Clear() ReleaseLocks(0, locksAcquired); } } - + public IEnumerator GetEnumerator() { Node[] buckets = _tables._buckets; @@ -429,7 +440,8 @@ private void GrowTable(Tables tables) newBuckets[newBucketNo] = new Node(current._value, current._hashcode, newBuckets[newBucketNo]); - checked { newCountPerLock[newLockNo]++; } + checked + { newCountPerLock[newLockNo]++; } current = next; } @@ -468,5 +480,5 @@ private void ReleaseLocks(int fromInclusive, int toExclusive) { for (int i = fromInclusive; i < toExclusive; i++) Monitor.Exit(_tables._locks[i]); - } -} \ No newline at end of file + } +} diff --git a/src/Kook.Net.Core/Utils/MentionUtils.cs b/src/Kook.Net.Core/Utils/MentionUtils.cs index 780dd3e1..37e529b0 100644 --- a/src/Kook.Net.Core/Utils/MentionUtils.cs +++ b/src/Kook.Net.Core/Utils/MentionUtils.cs @@ -1,4 +1,4 @@ -using System.Globalization; +using System.Globalization; using System.Text; using System.Text.RegularExpressions; @@ -220,27 +220,33 @@ internal static string Resolve(IMessage msg, int startIndex, TagHandling userHan switch (tag.Type) { case TagType.UserMention: - if (userHandling == TagHandling.Ignore) continue; + if (userHandling == TagHandling.Ignore) + continue; newText = ResolveUserMention(tag, userHandling); break; case TagType.ChannelMention: - if (channelHandling == TagHandling.Ignore) continue; + if (channelHandling == TagHandling.Ignore) + continue; newText = ResolveChannelMention(tag, channelHandling); break; case TagType.RoleMention: - if (roleHandling == TagHandling.Ignore) continue; + if (roleHandling == TagHandling.Ignore) + continue; newText = ResolveRoleMention(tag, roleHandling); break; case TagType.EveryoneMention: - if (everyoneHandling == TagHandling.Ignore) continue; + if (everyoneHandling == TagHandling.Ignore) + continue; newText = ResolveEveryoneMention(tag, everyoneHandling); break; case TagType.HereMention: - if (everyoneHandling == TagHandling.Ignore) continue; + if (everyoneHandling == TagHandling.Ignore) + continue; newText = ResolveHereMention(tag, everyoneHandling); break; case TagType.Emoji: - if (emojiHandling == TagHandling.Ignore) continue; + if (emojiHandling == TagHandling.Ignore) + continue; newText = ResolveEmoji(tag, emojiHandling); break; } @@ -385,7 +391,7 @@ internal static string ResolveEmoji(ITag tag, TagHandling mode) { if (mode != TagHandling.Remove) { - Emote emoji = (Emote) tag.Value; + Emote emoji = (Emote)tag.Value; //Remove if its name contains any bad chars (prevents a few tag exploits) for (int i = 0; i < emoji.Name.Length; i++) diff --git a/src/Kook.Net.Core/Utils/Paging/Page.cs b/src/Kook.Net.Core/Utils/Paging/Page.cs index 0e1bfcab..a55d5eb3 100644 --- a/src/Kook.Net.Core/Utils/Paging/Page.cs +++ b/src/Kook.Net.Core/Utils/Paging/Page.cs @@ -1,4 +1,4 @@ -using System.Collections; +using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; @@ -18,4 +18,4 @@ public Page(PageInfo info, IEnumerable source) int IReadOnlyCollection.Count => _items.Count; IEnumerator IEnumerable.GetEnumerator() => _items.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _items.GetEnumerator(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Utils/Paging/PageInfo.cs b/src/Kook.Net.Core/Utils/Paging/PageInfo.cs index a3112bcf..0a69ea8e 100644 --- a/src/Kook.Net.Core/Utils/Paging/PageInfo.cs +++ b/src/Kook.Net.Core/Utils/Paging/PageInfo.cs @@ -1,4 +1,4 @@ -namespace Kook; +namespace Kook; internal class PageInfo { @@ -19,4 +19,4 @@ internal PageInfo(Guid? pos, int? count, int pageSize) if (Count != null && Count.Value < PageSize) PageSize = Count.Value; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Utils/Paging/PagedEnumerator.cs b/src/Kook.Net.Core/Utils/Paging/PagedEnumerator.cs index fea8ba41..3dbdeb88 100644 --- a/src/Kook.Net.Core/Utils/Paging/PagedEnumerator.cs +++ b/src/Kook.Net.Core/Utils/Paging/PagedEnumerator.cs @@ -72,11 +72,11 @@ public async ValueTask MoveNextAsync() return true; } - + public ValueTask DisposeAsync() { Current = null; return default; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Utils/Permissions.cs b/src/Kook.Net.Core/Utils/Permissions.cs index 9dabd538..6e88ddb1 100644 --- a/src/Kook.Net.Core/Utils/Permissions.cs +++ b/src/Kook.Net.Core/Utils/Permissions.cs @@ -8,11 +8,11 @@ internal static class Permissions [MethodImpl(MethodImplOptions.AggressiveInlining)] public static PermValue GetValue(ulong allow, ulong deny, ChannelPermission flag) - => GetValue(allow, deny, (ulong) flag); + => GetValue(allow, deny, (ulong)flag); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static PermValue GetValue(ulong allow, ulong deny, GuildPermission flag) - => GetValue(allow, deny, (ulong) flag); + => GetValue(allow, deny, (ulong)flag); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static PermValue GetValue(ulong allow, ulong deny, ulong flag) @@ -27,22 +27,22 @@ public static PermValue GetValue(ulong allow, ulong deny, ulong flag) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GetValue(ulong value, ChannelPermission flag) - => GetValue(value, (ulong) flag); + => GetValue(value, (ulong)flag); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GetValue(ulong value, GuildPermission flag) - => GetValue(value, (ulong) flag); + => GetValue(value, (ulong)flag); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GetValue(ulong value, ulong flag) => HasFlag(value, flag); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void SetValue(ref ulong rawValue, bool? value, ChannelPermission flag) - => SetValue(ref rawValue, value, (ulong) flag); + => SetValue(ref rawValue, value, (ulong)flag); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void SetValue(ref ulong rawValue, bool? value, GuildPermission flag) - => SetValue(ref rawValue, value, (ulong) flag); + => SetValue(ref rawValue, value, (ulong)flag); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void SetValue(ref ulong rawValue, bool? value, ulong flag) @@ -58,11 +58,11 @@ public static void SetValue(ref ulong rawValue, bool? value, ulong flag) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void SetValue(ref ulong allow, ref ulong deny, PermValue? value, ChannelPermission flag) - => SetValue(ref allow, ref deny, value, (ulong) flag); + => SetValue(ref allow, ref deny, value, (ulong)flag); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void SetValue(ref ulong allow, ref ulong deny, PermValue? value, GuildPermission flag) - => SetValue(ref allow, ref deny, value, (ulong) flag); + => SetValue(ref allow, ref deny, value, (ulong)flag); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void SetValue(ref ulong allow, ref ulong deny, PermValue? value, ulong flag) @@ -95,8 +95,8 @@ public static void SetValue(ref ulong allow, ref ulong deny, PermValue? value, u [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void UnsetFlag(ref ulong value, ulong flag) => value &= ~flag; - - + + public static ChannelPermissions ToChannelPerms(IGuildChannel channel, ulong guildPermissions) => new ChannelPermissions(guildPermissions & ChannelPermissions.All(channel).RawValue); public static ulong ResolveGuild(IGuild guild, IGuildUser user) @@ -156,7 +156,7 @@ public static ulong ResolveChannel(IGuild guild, IGuildUser user, IGuildChannel //Give/Take User permissions perms = channel.GetPermissionOverwrite(user); if (perms != null) - resolvedPermissions = (resolvedPermissions & ~perms.Value.DenyValue) | perms.Value.AllowValue; + resolvedPermissions = (resolvedPermissions & ~perms.Value.DenyValue) | perms.Value.AllowValue; if (channel is ITextChannel) { @@ -177,4 +177,4 @@ public static ulong ResolveChannel(IGuild guild, IGuildUser user, IGuildChannel return resolvedPermissions; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Utils/Preconditions.cs b/src/Kook.Net.Core/Utils/Preconditions.cs index 1e7f1964..121b82b5 100644 --- a/src/Kook.Net.Core/Utils/Preconditions.cs +++ b/src/Kook.Net.Core/Utils/Preconditions.cs @@ -10,8 +10,10 @@ public class Preconditions private static ArgumentNullException CreateNotNullException(string name, string msg) { - if (msg == null) return new ArgumentNullException(paramName: name); - else return new ArgumentNullException(paramName: name, message: msg); + if (msg == null) + return new ArgumentNullException(paramName: name); + else + return new ArgumentNullException(paramName: name, message: msg); } #endregion @@ -22,21 +24,25 @@ private static ArgumentNullException CreateNotNullException(string name, string /// must not be . public static void NotNullOrEmpty(string obj, string name, string msg = null) { - if (obj == null) throw CreateNotNullException(name, msg); - if (obj.Length == 0) throw CreateNotEmptyException(name, msg); + if (obj == null) + throw CreateNotNullException(name, msg); + if (obj.Length == 0) + throw CreateNotEmptyException(name, msg); } /// cannot be blank. /// must not be . public static void NotNullOrWhitespace(string obj, string name, string msg = null) { - if (obj == null) throw CreateNotNullException(name, msg); - if (obj.Trim().Length == 0) throw CreateNotEmptyException(name, msg); - } + if (obj == null) + throw CreateNotNullException(name, msg); + if (obj.Trim().Length == 0) + throw CreateNotEmptyException(name, msg); + } private static ArgumentException CreateNotEmptyException(string name, string msg) => new ArgumentException(message: msg ?? "Argument cannot be blank.", paramName: name); #endregion - + #region Numerics /// Value may not be equal to . public static void NotEqual(sbyte obj, sbyte value, string name, string msg = null) { if (obj == value) throw CreateNotEqualException(name, msg, value); } @@ -77,7 +83,7 @@ private static ArgumentException CreateNotEmptyException(string name, string msg private static ArgumentException CreateNotEqualException(string name, string msg, T value) => new ArgumentException(message: msg ?? $"Value may not be equal to {value}.", paramName: name); - + /// Value must be at least . public static void AtLeast(sbyte obj, sbyte value, string name, string msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); } /// Value must be at least . @@ -113,7 +119,7 @@ private static ArgumentException CreateNotEqualException(string name, string private static ArgumentException CreateAtLeastException(string name, string msg, T value) => new ArgumentException(message: msg ?? $"Value must be at least {value}.", paramName: name); - + /// Value must be greater than . public static void GreaterThan(sbyte obj, sbyte value, string name, string msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); } /// Value must be greater than . @@ -149,7 +155,7 @@ private static ArgumentException CreateAtLeastException(string name, string m private static ArgumentException CreateGreaterThanException(string name, string msg, T value) => new ArgumentException(message: msg ?? $"Value must be greater than {value}.", paramName: name); - + /// Value must be at most . public static void AtMost(sbyte obj, sbyte value, string name, string msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); } /// Value must be at most . @@ -185,7 +191,7 @@ private static ArgumentException CreateGreaterThanException(string name, stri private static ArgumentException CreateAtMostException(string name, string msg, T value) => new ArgumentException(message: msg ?? $"Value must be at most {value}.", paramName: name); - + /// Value must be less than . public static void LessThan(sbyte obj, sbyte value, string name, string msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); } /// Value must be less than . @@ -222,4 +228,4 @@ private static ArgumentException CreateAtMostException(string name, string ms private static ArgumentException CreateLessThanException(string name, string msg, T value) => new ArgumentException(message: msg ?? $"Value must be less than {value}.", paramName: name); #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Utils/TokenUtils.cs b/src/Kook.Net.Core/Utils/TokenUtils.cs index abcfb48b..5567ada4 100644 --- a/src/Kook.Net.Core/Utils/TokenUtils.cs +++ b/src/Kook.Net.Core/Utils/TokenUtils.cs @@ -185,4 +185,4 @@ public static void ValidateToken(TokenType tokenType, string token) throw new ArgumentException(message: "Unrecognized TokenType.", paramName: nameof(token)); } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Core/Utils/UrlValidation.cs b/src/Kook.Net.Core/Utils/UrlValidation.cs index 774aa2fe..ce2d372f 100644 --- a/src/Kook.Net.Core/Utils/UrlValidation.cs +++ b/src/Kook.Net.Core/Utils/UrlValidation.cs @@ -14,7 +14,7 @@ public static bool Validate(string url) { if (string.IsNullOrEmpty(url)) return false; - if (!(url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) + if (!(url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))) throw new InvalidOperationException($"The url {url} must include a protocol (either HTTP or HTTPS)"); return true; @@ -51,10 +51,10 @@ public static bool ValidateKookAssetUrl(string url) { if (string.IsNullOrEmpty(url)) return false; - if (!Regex.IsMatch(url, - @"^https?:\/\/(img\.(kaiheila|kookapp)\.cn|kaiheila\.oss-cn-beijing\.aliyuncs\.com)\/(assets|attachments)\/\d{4}-\d{2}(\/\d{2})?\/\w{8,16}\.\w+$", + if (!Regex.IsMatch(url, + @"^https?:\/\/(img\.(kaiheila|kookapp)\.cn|kaiheila\.oss-cn-beijing\.aliyuncs\.com)\/(assets|attachments)\/\d{4}-\d{2}(\/\d{2})?\/\w{8,16}\.\w+$", RegexOptions.Compiled | RegexOptions.IgnoreCase)) throw new InvalidOperationException($"The url {url} must be a valid Kook asset URL"); return true; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/Core/Entities/Guilds/GuildProperties.cs b/src/Kook.Net.Experimental/Core/Entities/Guilds/GuildProperties.cs index 7f0be3cc..b7a438fd 100644 --- a/src/Kook.Net.Experimental/Core/Entities/Guilds/GuildProperties.cs +++ b/src/Kook.Net.Experimental/Core/Entities/Guilds/GuildProperties.cs @@ -77,4 +77,4 @@ public class GuildProperties /// set to 0 instead. /// public ITextChannel WidgetChannel { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/Core/Entities/Guilds/IVoiceRegion.cs b/src/Kook.Net.Experimental/Core/Entities/Guilds/IVoiceRegion.cs index e43c271a..dee48beb 100644 --- a/src/Kook.Net.Experimental/Core/Entities/Guilds/IVoiceRegion.cs +++ b/src/Kook.Net.Experimental/Core/Entities/Guilds/IVoiceRegion.cs @@ -32,4 +32,4 @@ public interface IVoiceRegion /// A decimal between 0.0 and 1.0 that represents the crowding of this voice region. /// decimal Crowding { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/Rest/API/Common/VoiceRegion.cs b/src/Kook.Net.Experimental/Rest/API/Common/VoiceRegion.cs index 2ee2726f..736143d7 100644 --- a/src/Kook.Net.Experimental/Rest/API/Common/VoiceRegion.cs +++ b/src/Kook.Net.Experimental/Rest/API/Common/VoiceRegion.cs @@ -1,4 +1,4 @@ -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; namespace Kook.API { @@ -11,4 +11,4 @@ internal class VoiceRegion [JsonPropertyName("crowding")] public int Crowding { get; set; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/Rest/API/Rest/CreateGuildParams.cs b/src/Kook.Net.Experimental/Rest/API/Rest/CreateGuildParams.cs index 0ade87a1..2c7ea929 100644 --- a/src/Kook.Net.Experimental/Rest/API/Rest/CreateGuildParams.cs +++ b/src/Kook.Net.Experimental/Rest/API/Rest/CreateGuildParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; diff --git a/src/Kook.Net.Experimental/Rest/API/Rest/DeleteGuildParams.cs b/src/Kook.Net.Experimental/Rest/API/Rest/DeleteGuildParams.cs index e07a62d5..3ea5cdf7 100644 --- a/src/Kook.Net.Experimental/Rest/API/Rest/DeleteGuildParams.cs +++ b/src/Kook.Net.Experimental/Rest/API/Rest/DeleteGuildParams.cs @@ -7,5 +7,5 @@ internal class DeleteGuildParams [JsonPropertyName("guild_id")] public ulong GuildId { get; set; } - public static implicit operator DeleteGuildParams(ulong guildId) => new() {GuildId = guildId}; -} \ No newline at end of file + public static implicit operator DeleteGuildParams(ulong guildId) => new() { GuildId = guildId }; +} diff --git a/src/Kook.Net.Experimental/Rest/API/Rest/DisconnectUserParams.cs b/src/Kook.Net.Experimental/Rest/API/Rest/DisconnectUserParams.cs index 0442a21b..9854e0a1 100644 --- a/src/Kook.Net.Experimental/Rest/API/Rest/DisconnectUserParams.cs +++ b/src/Kook.Net.Experimental/Rest/API/Rest/DisconnectUserParams.cs @@ -1,4 +1,4 @@ -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -9,4 +9,4 @@ internal class DisconnectUserParams [JsonPropertyName("user_id")] public ulong UserId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/Rest/API/Rest/ModifyGuildParams.cs b/src/Kook.Net.Experimental/Rest/API/Rest/ModifyGuildParams.cs index 0b21be73..983deee0 100644 --- a/src/Kook.Net.Experimental/Rest/API/Rest/ModifyGuildParams.cs +++ b/src/Kook.Net.Experimental/Rest/API/Rest/ModifyGuildParams.cs @@ -21,4 +21,4 @@ internal class ModifyGuildParams [JsonPropertyName("widget_invite_channel_id")] public ulong? WidgetChannelId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/Rest/API/Rest/SyncChannelPermissionsParams.cs b/src/Kook.Net.Experimental/Rest/API/Rest/SyncChannelPermissionsParams.cs index 13aa8da2..d28b7508 100644 --- a/src/Kook.Net.Experimental/Rest/API/Rest/SyncChannelPermissionsParams.cs +++ b/src/Kook.Net.Experimental/Rest/API/Rest/SyncChannelPermissionsParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -12,4 +12,4 @@ public SyncChannelPermissionsParams(ulong channelId) { ChannelId = channelId; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/Rest/Entities/Channels/ExperimentalChannelHelper.cs b/src/Kook.Net.Experimental/Rest/Entities/Channels/ExperimentalChannelHelper.cs index b426abe1..8eb89512 100644 --- a/src/Kook.Net.Experimental/Rest/Entities/Channels/ExperimentalChannelHelper.cs +++ b/src/Kook.Net.Experimental/Rest/Entities/Channels/ExperimentalChannelHelper.cs @@ -35,4 +35,4 @@ public static async Task DisconnectUserAsync(IVoiceChannel channel, BaseKookClie #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/Rest/Entities/Channels/RestTextChannelExperimentalExtensions.cs b/src/Kook.Net.Experimental/Rest/Entities/Channels/RestTextChannelExperimentalExtensions.cs index b7c8ff83..e93bba71 100644 --- a/src/Kook.Net.Experimental/Rest/Entities/Channels/RestTextChannelExperimentalExtensions.cs +++ b/src/Kook.Net.Experimental/Rest/Entities/Channels/RestTextChannelExperimentalExtensions.cs @@ -18,4 +18,4 @@ public static class RestTextChannelExperimentalExtensions /// public static Task SyncPermissionsAsync(this RestTextChannel channel, RequestOptions options = null) => ExperimentalChannelHelper.SyncPermissionsAsync(channel, channel.Kook, options); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/Rest/Entities/Channels/RestVoiceChannelExperimentalExtensions.cs b/src/Kook.Net.Experimental/Rest/Entities/Channels/RestVoiceChannelExperimentalExtensions.cs index 00eff1d7..3ffe22f6 100644 --- a/src/Kook.Net.Experimental/Rest/Entities/Channels/RestVoiceChannelExperimentalExtensions.cs +++ b/src/Kook.Net.Experimental/Rest/Entities/Channels/RestVoiceChannelExperimentalExtensions.cs @@ -35,4 +35,4 @@ public static Task SyncPermissionsAsync(this RestVoiceChannel channel, RequestOp /// public static Task DisconnectUserAsync(this RestVoiceChannel channel, IGuildUser user, RequestOptions options = null) => ExperimentalChannelHelper.DisconnectUserAsync(channel, channel.Kook, user, options); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/Rest/Entities/Guilds/ExperimentalGuildHelper.cs b/src/Kook.Net.Experimental/Rest/Entities/Guilds/ExperimentalGuildHelper.cs index 39abe053..a3d04575 100644 --- a/src/Kook.Net.Experimental/Rest/Entities/Guilds/ExperimentalGuildHelper.cs +++ b/src/Kook.Net.Experimental/Rest/Entities/Guilds/ExperimentalGuildHelper.cs @@ -1,5 +1,5 @@ -using RichModel = Kook.API.Rest.RichGuild; using Kook.Rest.Extensions; +using RichModel = Kook.API.Rest.RichGuild; namespace Kook.Rest; @@ -9,7 +9,8 @@ internal static class ExperimentalGuildHelper public static async Task ModifyAsync(IGuild guild, BaseKookClient client, Action func, RequestOptions options) { - if (func == null) throw new ArgumentNullException(nameof(func)); + if (func == null) + throw new ArgumentNullException(nameof(func)); var args = new GuildProperties(); func(args); @@ -48,4 +49,4 @@ public static async Task DeleteAsync(IGuild guild, BaseKookClient client, { await client.ApiClient.DeleteGuildAsync(guild.Id, options).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/Rest/Entities/Guilds/RestVoiceRegion.cs b/src/Kook.Net.Experimental/Rest/Entities/Guilds/RestVoiceRegion.cs index 83e711de..82cbac3a 100644 --- a/src/Kook.Net.Experimental/Rest/Entities/Guilds/RestVoiceRegion.cs +++ b/src/Kook.Net.Experimental/Rest/Entities/Guilds/RestVoiceRegion.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; using Model = Kook.API.VoiceRegion; namespace Kook.Rest; @@ -38,4 +38,4 @@ internal void Update(Model model) public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Id}, {Crowding:F2}%)"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/Rest/ExperimentalClientHelper.cs b/src/Kook.Net.Experimental/Rest/ExperimentalClientHelper.cs index 6ebde7bb..7d706f2f 100644 --- a/src/Kook.Net.Experimental/Rest/ExperimentalClientHelper.cs +++ b/src/Kook.Net.Experimental/Rest/ExperimentalClientHelper.cs @@ -1,6 +1,6 @@ -using System.Collections.Immutable; using Kook.API.Rest; using Kook.Rest.Extensions; +using System.Collections.Immutable; namespace Kook.Rest; @@ -49,4 +49,4 @@ public static async Task GetVoiceRegionAsync(BaseKookClient cli } #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/Rest/KookRestApiClientExperimentalExtensions.cs b/src/Kook.Net.Experimental/Rest/KookRestApiClientExperimentalExtensions.cs index 1a952dac..f373c8e1 100644 --- a/src/Kook.Net.Experimental/Rest/KookRestApiClientExperimentalExtensions.cs +++ b/src/Kook.Net.Experimental/Rest/KookRestApiClientExperimentalExtensions.cs @@ -68,7 +68,7 @@ public static IAsyncEnumerable> GetVoiceRegions options = RequestOptions.CreateOrClone(options); var ids = new KookRestApiClient.BucketIds(); PageMeta pageMeta = new(fromPage, limit); - return client.SendPagedAsync(HttpMethod.Get,(pageSize, page) => $"guild/regions&page_size={pageSize}&page={page}", + return client.SendPagedAsync(HttpMethod.Get, (pageSize, page) => $"guild/regions&page_size={pageSize}&page={page}", ids, clientBucket: ClientBucketType.SendEdit, pageMeta: pageMeta, options: options); } @@ -89,4 +89,4 @@ public static async Task DisconnectUserAsync(this KookRestApiClient client, Disc #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/Rest/Net/Converters/ImageBase64DataUriConverter.cs b/src/Kook.Net.Experimental/Rest/Net/Converters/ImageBase64DataUriConverter.cs index 3def9899..1069e712 100644 --- a/src/Kook.Net.Experimental/Rest/Net/Converters/ImageBase64DataUriConverter.cs +++ b/src/Kook.Net.Experimental/Rest/Net/Converters/ImageBase64DataUriConverter.cs @@ -43,4 +43,4 @@ public override void Write(Utf8JsonWriter writer, Image? value, JsonSerializerOp : "png"; writer.WriteStringValue($"data:image/{extension};base64,{base64}"); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/WebSocket/Entities/Channels/SocketTextChannelExperimentalExtensions.cs b/src/Kook.Net.Experimental/WebSocket/Entities/Channels/SocketTextChannelExperimentalExtensions.cs index 65d3c48d..847bdaa5 100644 --- a/src/Kook.Net.Experimental/WebSocket/Entities/Channels/SocketTextChannelExperimentalExtensions.cs +++ b/src/Kook.Net.Experimental/WebSocket/Entities/Channels/SocketTextChannelExperimentalExtensions.cs @@ -20,4 +20,4 @@ public static class SocketTextChannelExperimentalExtensions /// public static Task SyncPermissionsAsync(this SocketTextChannel channel, RequestOptions options = null) => ExperimentalChannelHelper.SyncPermissionsAsync(channel, channel.Kook, options); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Experimental/WebSocket/Entities/Channels/SocketVoiceChannelExperimentalExtensions.cs b/src/Kook.Net.Experimental/WebSocket/Entities/Channels/SocketVoiceChannelExperimentalExtensions.cs index a33a2a43..37e7cd5d 100644 --- a/src/Kook.Net.Experimental/WebSocket/Entities/Channels/SocketVoiceChannelExperimentalExtensions.cs +++ b/src/Kook.Net.Experimental/WebSocket/Entities/Channels/SocketVoiceChannelExperimentalExtensions.cs @@ -38,4 +38,4 @@ public static Task SyncPermissionsAsync(this SocketVoiceChannel channel, Request /// public static Task DisconnectUserAsync(this SocketVoiceChannel channel, IGuildUser user, RequestOptions options = null) => ExperimentalChannelHelper.DisconnectUserAsync(channel, channel.Kook, user, options); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Attachment.cs b/src/Kook.Net.Rest/API/Common/Attachment.cs index c7d58070..ebc04f11 100644 --- a/src/Kook.Net.Rest/API/Common/Attachment.cs +++ b/src/Kook.Net.Rest/API/Common/Attachment.cs @@ -12,4 +12,4 @@ internal class Attachment [JsonPropertyName("duration")] public double? Duration { get; set; } [JsonPropertyName("width")] public int? Width { get; set; } [JsonPropertyName("height")] public int? Height { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Ban.cs b/src/Kook.Net.Rest/API/Common/Ban.cs index 82ddbac4..4ec039f8 100644 --- a/src/Kook.Net.Rest/API/Common/Ban.cs +++ b/src/Kook.Net.Rest/API/Common/Ban.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -17,4 +17,4 @@ internal class Ban [JsonPropertyName("user")] public User User { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Card.cs b/src/Kook.Net.Rest/API/Common/Cards/Card.cs index 833d4584..2ef406ea 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Card.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Card.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -19,4 +19,4 @@ internal class Card : CardBase [JsonPropertyName("modules")] public ModuleBase[] Modules { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/CardBase.cs b/src/Kook.Net.Rest/API/Common/Cards/CardBase.cs index c62ae51d..d6c6f486 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/CardBase.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/CardBase.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -8,4 +8,4 @@ internal class CardBase : ICard [JsonPropertyName("type")] [JsonConverter(typeof(CardTypeConverter))] public CardType Type { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Elements/ButtonElement.cs b/src/Kook.Net.Rest/API/Common/Cards/Elements/ButtonElement.cs index ca9adc3a..f4b7b0d7 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Elements/ButtonElement.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Elements/ButtonElement.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -17,4 +17,4 @@ internal class ButtonElement : ElementBase [JsonPropertyName("text")] public ElementBase Text { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Elements/ElementBase.cs b/src/Kook.Net.Rest/API/Common/Cards/Elements/ElementBase.cs index 85003ec1..399269a0 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Elements/ElementBase.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Elements/ElementBase.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -8,4 +8,4 @@ internal class ElementBase : IElement [JsonPropertyName("type")] [JsonConverter(typeof(ElementTypeConverter))] public ElementType Type { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Elements/IElement.cs b/src/Kook.Net.Rest/API/Common/Cards/Elements/IElement.cs index c217c26a..dbd65ae0 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Elements/IElement.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Elements/IElement.cs @@ -3,4 +3,4 @@ namespace Kook.API; internal interface IElement { ElementType Type { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Elements/ImageElement.cs b/src/Kook.Net.Rest/API/Common/Cards/Elements/ImageElement.cs index 0a432562..e79ca80d 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Elements/ImageElement.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Elements/ImageElement.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -13,4 +13,4 @@ internal class ImageElement : ElementBase public ImageSize? Size { get; set; } [JsonPropertyName("circle")] public bool? Circle { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Elements/KMarkdownElement.cs b/src/Kook.Net.Rest/API/Common/Cards/Elements/KMarkdownElement.cs index 1753e411..4c36211f 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Elements/KMarkdownElement.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Elements/KMarkdownElement.cs @@ -6,4 +6,4 @@ internal class KMarkdownElement : ElementBase { [JsonPropertyName("content")] public string Content { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Elements/ParagraphStruct.cs b/src/Kook.Net.Rest/API/Common/Cards/Elements/ParagraphStruct.cs index 94b659a5..d88a7a79 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Elements/ParagraphStruct.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Elements/ParagraphStruct.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -10,4 +10,4 @@ internal class ParagraphStruct : ElementBase [JsonPropertyName("fields")] public ElementBase[] Fields { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Elements/PlainTextElement.cs b/src/Kook.Net.Rest/API/Common/Cards/Elements/PlainTextElement.cs index c3d75343..76a4738a 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Elements/PlainTextElement.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Elements/PlainTextElement.cs @@ -8,4 +8,4 @@ internal class PlainTextElement : ElementBase public string Content { get; set; } [JsonPropertyName("emoji")] public bool Emoji { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/ICard.cs b/src/Kook.Net.Rest/API/Common/Cards/ICard.cs index 3f59d483..befed4b6 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/ICard.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/ICard.cs @@ -3,4 +3,4 @@ namespace Kook.API; internal interface ICard { CardType Type { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Modules/ActionGroupModule.cs b/src/Kook.Net.Rest/API/Common/Cards/Modules/ActionGroupModule.cs index 6221b816..533162cc 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Modules/ActionGroupModule.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Modules/ActionGroupModule.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -7,4 +7,4 @@ internal class ActionGroupModule : ModuleBase { [JsonPropertyName("elements")] public ButtonElement[] Elements { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Modules/AudioModule.cs b/src/Kook.Net.Rest/API/Common/Cards/Modules/AudioModule.cs index af8f7f76..ed53c744 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Modules/AudioModule.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Modules/AudioModule.cs @@ -7,4 +7,4 @@ internal class AudioModule : ModuleBase [JsonPropertyName("src")] public string Source { get; set; } [JsonPropertyName("title")] public string Title { get; set; } [JsonPropertyName("cover")] public string Cover { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Modules/ContainerModule.cs b/src/Kook.Net.Rest/API/Common/Cards/Modules/ContainerModule.cs index 1ce9826c..da8c352e 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Modules/ContainerModule.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Modules/ContainerModule.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -7,4 +7,4 @@ internal class ContainerModule : ModuleBase { [JsonPropertyName("elements")] public ImageElement[] Elements { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Modules/ContextModule.cs b/src/Kook.Net.Rest/API/Common/Cards/Modules/ContextModule.cs index f6a3ff04..a3e9be60 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Modules/ContextModule.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Modules/ContextModule.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -7,4 +7,4 @@ internal class ContextModule : ModuleBase { [JsonPropertyName("elements")] public ElementBase[] Elements { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Modules/CountdownModule.cs b/src/Kook.Net.Rest/API/Common/Cards/Modules/CountdownModule.cs index 1500ce60..26033795 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Modules/CountdownModule.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Modules/CountdownModule.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -8,12 +8,12 @@ internal class CountdownModule : ModuleBase [JsonPropertyName("endTime")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset EndTime { get; set; } - + [JsonPropertyName("startTime")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset? StartTime { get; set; } - + [JsonPropertyName("mode")] [JsonConverter(typeof(CountdownModeConverter))] public CountdownMode Mode { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Modules/DividerModule.cs b/src/Kook.Net.Rest/API/Common/Cards/Modules/DividerModule.cs index d09183d8..92a02935 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Modules/DividerModule.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Modules/DividerModule.cs @@ -1,8 +1,8 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; internal class DividerModule : ModuleBase { -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Modules/FileModule.cs b/src/Kook.Net.Rest/API/Common/Cards/Modules/FileModule.cs index 609ac70b..077fdc29 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Modules/FileModule.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Modules/FileModule.cs @@ -6,4 +6,4 @@ internal class FileModule : ModuleBase { [JsonPropertyName("src")] public string Source { get; set; } [JsonPropertyName("title")] public string Title { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Modules/HeaderModule.cs b/src/Kook.Net.Rest/API/Common/Cards/Modules/HeaderModule.cs index 1b6bcd73..d514b338 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Modules/HeaderModule.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Modules/HeaderModule.cs @@ -6,4 +6,4 @@ internal class HeaderModule : ModuleBase { [JsonPropertyName("text")] public PlainTextElement Text { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Modules/IModule.cs b/src/Kook.Net.Rest/API/Common/Cards/Modules/IModule.cs index 9e7bf76f..5c20f5d0 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Modules/IModule.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Modules/IModule.cs @@ -1,4 +1,4 @@ -namespace Kook.API; +namespace Kook.API; internal interface IModule { @@ -6,4 +6,4 @@ internal interface IModule /// 模块类型 /// ModuleType Type { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Modules/ImageGroupModule.cs b/src/Kook.Net.Rest/API/Common/Cards/Modules/ImageGroupModule.cs index a2605b14..c5910dbb 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Modules/ImageGroupModule.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Modules/ImageGroupModule.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -7,4 +7,4 @@ internal class ImageGroupModule : ModuleBase { [JsonPropertyName("elements")] public ImageElement[] Elements { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Modules/InviteModule.cs b/src/Kook.Net.Rest/API/Common/Cards/Modules/InviteModule.cs index 8caa8a60..a74dd741 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Modules/InviteModule.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Modules/InviteModule.cs @@ -6,4 +6,4 @@ internal class InviteModule : ModuleBase { [JsonPropertyName("code")] public string Code { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Modules/ModuleBase.cs b/src/Kook.Net.Rest/API/Common/Cards/Modules/ModuleBase.cs index abf4bdc4..fdbbf79c 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Modules/ModuleBase.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Modules/ModuleBase.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -8,4 +8,4 @@ internal class ModuleBase : IModule [JsonPropertyName("type")] [JsonConverter(typeof(ModuleTypeConverter))] public ModuleType Type { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Modules/SectionModule.cs b/src/Kook.Net.Rest/API/Common/Cards/Modules/SectionModule.cs index b8327fd5..74187ecc 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Modules/SectionModule.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Modules/SectionModule.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -15,4 +15,4 @@ internal class SectionModule : ModuleBase [JsonPropertyName("accessory")] public ElementBase Accessory { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Cards/Modules/VideoModule.cs b/src/Kook.Net.Rest/API/Common/Cards/Modules/VideoModule.cs index 97941336..70173969 100644 --- a/src/Kook.Net.Rest/API/Common/Cards/Modules/VideoModule.cs +++ b/src/Kook.Net.Rest/API/Common/Cards/Modules/VideoModule.cs @@ -6,4 +6,4 @@ internal class VideoModule : ModuleBase { [JsonPropertyName("src")] public string Source { get; set; } [JsonPropertyName("title")] public string Title { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Channel.cs b/src/Kook.Net.Rest/API/Common/Channel.cs index f7d0e0dc..8478097a 100644 --- a/src/Kook.Net.Rest/API/Common/Channel.cs +++ b/src/Kook.Net.Rest/API/Common/Channel.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -29,19 +29,19 @@ internal class Channel [JsonPropertyName("permission_overwrites")] public RolePermissionOverwrite[] RolePermissionOverwrites { get; set; } - [JsonPropertyName("permission_users")] + [JsonPropertyName("permission_users")] public UserPermissionOverwrite[] UserPermissionOverwrites { get; set; } - + [JsonPropertyName("channels")] public Channel[] Channels { get; set; } - - [JsonPropertyName("permission_sync")] + + [JsonPropertyName("permission_sync")] [JsonConverter(typeof(NullableNumberBooleanConverter))] public bool? PermissionSync { get; set; } - + // Text [JsonPropertyName("topic")] public string Topic { get; set; } [JsonPropertyName("slow_mode")] public int SlowMode { get; set; } - + // Voice [JsonPropertyName("limit_amount")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -58,4 +58,4 @@ internal class Channel [JsonPropertyName("has_password")] public bool HasPassword { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/DirectMessage.cs b/src/Kook.Net.Rest/API/Common/DirectMessage.cs index 326038b5..e16afcd9 100644 --- a/src/Kook.Net.Rest/API/Common/DirectMessage.cs +++ b/src/Kook.Net.Rest/API/Common/DirectMessage.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -7,13 +7,13 @@ internal class DirectMessage { [JsonPropertyName("id")] public Guid Id { get; set; } - + [JsonPropertyName("type")] public MessageType Type { get; set; } - + [JsonPropertyName("content")] public string Content { get; set; } - + [JsonPropertyName("embeds")] public EmbedBase[] Embeds { get; set; } @@ -23,7 +23,7 @@ internal class DirectMessage [JsonPropertyName("create_at")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset CreateAt { get; set; } - + [JsonPropertyName("update_at")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset UpdateAt { get; set; } @@ -42,7 +42,7 @@ internal class DirectMessage [JsonPropertyName("quote")] public Quote Quote { get; set; } - + [JsonPropertyName("mention_info")] public MentionInfo MentionInfo { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Embeds/BilibiliVideoEmbed.cs b/src/Kook.Net.Rest/API/Common/Embeds/BilibiliVideoEmbed.cs index 023346da..edbc1e99 100644 --- a/src/Kook.Net.Rest/API/Common/Embeds/BilibiliVideoEmbed.cs +++ b/src/Kook.Net.Rest/API/Common/Embeds/BilibiliVideoEmbed.cs @@ -6,19 +6,19 @@ internal class BilibiliVideoEmbed : EmbedBase { [JsonPropertyName("origin_url")] public string OriginUrl { get; set; } - + [JsonPropertyName("av_no")] public string BvNumber { get; set; } - + [JsonPropertyName("iframe_path")] public string IframePath { get; set; } - + [JsonPropertyName("duration")] public int Duration { get; set; } - + [JsonPropertyName("title")] public string Title { get; set; } - + [JsonPropertyName("pic")] public string Cover { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Embeds/EmbedBase.cs b/src/Kook.Net.Rest/API/Common/Embeds/EmbedBase.cs index 61db0493..1c776a6f 100644 --- a/src/Kook.Net.Rest/API/Common/Embeds/EmbedBase.cs +++ b/src/Kook.Net.Rest/API/Common/Embeds/EmbedBase.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -12,4 +12,4 @@ internal class EmbedBase : IEmbed [JsonPropertyName("url")] public string Url { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Embeds/IEmbed.cs b/src/Kook.Net.Rest/API/Common/Embeds/IEmbed.cs index 169ad16b..a8f82056 100644 --- a/src/Kook.Net.Rest/API/Common/Embeds/IEmbed.cs +++ b/src/Kook.Net.Rest/API/Common/Embeds/IEmbed.cs @@ -5,4 +5,4 @@ internal interface IEmbed EmbedType Type { get; } string Url { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Embeds/ImageEmbed.cs b/src/Kook.Net.Rest/API/Common/Embeds/ImageEmbed.cs index aedd17b6..68a5ac6c 100644 --- a/src/Kook.Net.Rest/API/Common/Embeds/ImageEmbed.cs +++ b/src/Kook.Net.Rest/API/Common/Embeds/ImageEmbed.cs @@ -6,4 +6,4 @@ internal class ImageEmbed : EmbedBase { [JsonPropertyName("origin_url")] public string OriginUrl { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Embeds/LinkEmbed.cs b/src/Kook.Net.Rest/API/Common/Embeds/LinkEmbed.cs index d4e071cf..3baf525b 100644 --- a/src/Kook.Net.Rest/API/Common/Embeds/LinkEmbed.cs +++ b/src/Kook.Net.Rest/API/Common/Embeds/LinkEmbed.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -20,4 +20,4 @@ internal class LinkEmbed : EmbedBase [JsonPropertyName("image")] public string Image { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Embeds/NotImplementedEmbed.cs b/src/Kook.Net.Rest/API/Common/Embeds/NotImplementedEmbed.cs index 61b2e819..f1c04ca2 100644 --- a/src/Kook.Net.Rest/API/Common/Embeds/NotImplementedEmbed.cs +++ b/src/Kook.Net.Rest/API/Common/Embeds/NotImplementedEmbed.cs @@ -12,6 +12,6 @@ internal NotImplementedEmbed(string rawType, string url, JsonNode rawJsonNode) } public string RawType { get; set; } - + public JsonNode RawJsonNode { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Emoji.cs b/src/Kook.Net.Rest/API/Common/Emoji.cs index 018c3471..90f28034 100644 --- a/src/Kook.Net.Rest/API/Common/Emoji.cs +++ b/src/Kook.Net.Rest/API/Common/Emoji.cs @@ -6,13 +6,13 @@ internal class Emoji { [JsonPropertyName("emoji_type")] public EmojiType Type { get; set; } - + [JsonPropertyName("id")] public string Id { get; set; } - + [JsonPropertyName("name")] public string Name { get; set; } [JsonPropertyName("user_info")] public User UploadedBy { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Game.cs b/src/Kook.Net.Rest/API/Common/Game.cs index 302cff66..d8cfced9 100644 --- a/src/Kook.Net.Rest/API/Common/Game.cs +++ b/src/Kook.Net.Rest/API/Common/Game.cs @@ -6,25 +6,25 @@ internal class Game { [JsonPropertyName("id")] public int Id { get; set; } - + [JsonPropertyName("name")] public string Name { get; set; } - + [JsonPropertyName("type")] public GameType Type { get; set; } - + [JsonPropertyName("options")] public string Options { get; set; } - + [JsonPropertyName("kmhook_admin")] public bool KmHookAdmin { get; set; } - + [JsonPropertyName("process_name")] public string[] ProcessNames { get; set; } - + [JsonPropertyName("product_name")] public string[] ProductNames { get; set; } - + [JsonPropertyName("icon")] public string Icon { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Guild.cs b/src/Kook.Net.Rest/API/Common/Guild.cs index 39ad70d5..c991d1ad 100644 --- a/src/Kook.Net.Rest/API/Common/Guild.cs +++ b/src/Kook.Net.Rest/API/Common/Guild.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -45,4 +45,4 @@ internal class Guild [JsonPropertyName("channels")] public Channel[] Channels { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Intimacy.cs b/src/Kook.Net.Rest/API/Common/Intimacy.cs index 789450e1..1b023eed 100644 --- a/src/Kook.Net.Rest/API/Common/Intimacy.cs +++ b/src/Kook.Net.Rest/API/Common/Intimacy.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -11,7 +11,7 @@ internal class Intimacy [JsonPropertyName("last_read")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset LastReadAt { get; set; } - + [JsonPropertyName("last_modify")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset LastModifyAt { get; set; } @@ -26,4 +26,4 @@ internal class IntimacyImage public uint Id { get; set; } [JsonPropertyName("url")] public string Url { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Invite.cs b/src/Kook.Net.Rest/API/Common/Invite.cs index ac4d2d0c..3dc6f9fb 100644 --- a/src/Kook.Net.Rest/API/Common/Invite.cs +++ b/src/Kook.Net.Rest/API/Common/Invite.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -20,18 +20,18 @@ internal class Invite [JsonPropertyName("url_code")] public string UrlCode { get; set; } [JsonPropertyName("url")] public string Url { get; set; } [JsonPropertyName("user")] public User Inviter { get; set; } - - [JsonPropertyName("expire_time")] + + [JsonPropertyName("expire_time")] [JsonConverter(typeof(NullableDateTimeOffsetConverter))] public DateTimeOffset? ExpiresAt { get; set; } [JsonPropertyName("remaining_times")] public int RemainingTimes { get; set; } - [JsonPropertyName("using_times")] + [JsonPropertyName("using_times")] public int UsingTimes { get; set; } [JsonPropertyName("duration")] [JsonConverter(typeof(NullableTimeSpanConverter))] public TimeSpan? Duration { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/MentionInfo.cs b/src/Kook.Net.Rest/API/Common/MentionInfo.cs index 5cfda1b9..c08b9809 100644 --- a/src/Kook.Net.Rest/API/Common/MentionInfo.cs +++ b/src/Kook.Net.Rest/API/Common/MentionInfo.cs @@ -12,4 +12,4 @@ internal class MentionInfo public MentionedChannel[] MentionedChannels { get; set; } [JsonPropertyName("item_part")] public Poke[] Pokes { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/MentionRole.cs b/src/Kook.Net.Rest/API/Common/MentionRole.cs index 1a0cbcad..fca23d53 100644 --- a/src/Kook.Net.Rest/API/Common/MentionRole.cs +++ b/src/Kook.Net.Rest/API/Common/MentionRole.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -16,4 +16,4 @@ internal class MentionRole [JsonPropertyName("hoist")] public int Hoist { get; set; } [JsonPropertyName("mentionable")] public int Mentionable { get; set; } [JsonPropertyName("permissions")] public ulong Permissions { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/MentionedChannel.cs b/src/Kook.Net.Rest/API/Common/MentionedChannel.cs index 987e7290..cb1052f2 100644 --- a/src/Kook.Net.Rest/API/Common/MentionedChannel.cs +++ b/src/Kook.Net.Rest/API/Common/MentionedChannel.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -11,4 +11,4 @@ internal class MentionedChannel public ulong GuildId { get; set; } [JsonPropertyName("name")] public string Name { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/MentionedUser.cs b/src/Kook.Net.Rest/API/Common/MentionedUser.cs index b59b4d38..8c9866a9 100644 --- a/src/Kook.Net.Rest/API/Common/MentionedUser.cs +++ b/src/Kook.Net.Rest/API/Common/MentionedUser.cs @@ -8,4 +8,4 @@ internal class MentionedUser [JsonPropertyName("username")] public string Username { get; set; } [JsonPropertyName("full_name")] public string FullName { get; set; } [JsonPropertyName("avatar")] public string Avatar { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Message.cs b/src/Kook.Net.Rest/API/Common/Message.cs index 0716de02..5d17464b 100644 --- a/src/Kook.Net.Rest/API/Common/Message.cs +++ b/src/Kook.Net.Rest/API/Common/Message.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -7,13 +7,13 @@ internal class Message { [JsonPropertyName("id")] public Guid Id { get; set; } - + [JsonPropertyName("type")] public MessageType Type { get; set; } - + [JsonPropertyName("content")] public string Content { get; set; } - + [JsonPropertyName("mention")] public ulong[] MentionedUsers { get; set; } @@ -35,14 +35,14 @@ internal class Message [JsonPropertyName("create_at")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset CreateAt { get; set; } - + [JsonPropertyName("updated_at")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset UpdateAt { get; set; } [JsonPropertyName("reactions")] public Reaction[] Reactions { get; set; } - + [JsonPropertyName("author")] public User Author { get; set; } @@ -57,4 +57,4 @@ internal class Message [JsonPropertyName("mention_info")] public MentionInfo MentionInfo { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Pokes/IPokeResource.cs b/src/Kook.Net.Rest/API/Common/Pokes/IPokeResource.cs index a09d97c3..c5fe411b 100644 --- a/src/Kook.Net.Rest/API/Common/Pokes/IPokeResource.cs +++ b/src/Kook.Net.Rest/API/Common/Pokes/IPokeResource.cs @@ -3,4 +3,4 @@ namespace Kook.API; internal interface IPokeResource { PokeResourceType Type { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Pokes/ImageAnimationPokeResource.cs b/src/Kook.Net.Rest/API/Common/Pokes/ImageAnimationPokeResource.cs index a0b33715..6e643bd1 100644 --- a/src/Kook.Net.Rest/API/Common/Pokes/ImageAnimationPokeResource.cs +++ b/src/Kook.Net.Rest/API/Common/Pokes/ImageAnimationPokeResource.cs @@ -20,4 +20,4 @@ internal class ImageAnimationPokeResource : PokeResourceBase public int Height { get; set; } [JsonPropertyName("percent")] public int Percent { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Pokes/NotImplementedPokeResource.cs b/src/Kook.Net.Rest/API/Common/Pokes/NotImplementedPokeResource.cs index 2ef4b3ca..7ccefdce 100644 --- a/src/Kook.Net.Rest/API/Common/Pokes/NotImplementedPokeResource.cs +++ b/src/Kook.Net.Rest/API/Common/Pokes/NotImplementedPokeResource.cs @@ -11,6 +11,6 @@ internal NotImplementedPokeResource(string rawType, JsonNode rawJsonNode) } public string RawType { get; set; } - + public JsonNode RawJsonNode { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Pokes/PokeQualityResource.cs b/src/Kook.Net.Rest/API/Common/Pokes/PokeQualityResource.cs index b4cd0f24..3744a8b6 100644 --- a/src/Kook.Net.Rest/API/Common/Pokes/PokeQualityResource.cs +++ b/src/Kook.Net.Rest/API/Common/Pokes/PokeQualityResource.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -12,4 +12,4 @@ internal class PokeQualityResource public string Small { get; set; } [JsonPropertyName("big")] public string Big { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Pokes/PokeResourceBase.cs b/src/Kook.Net.Rest/API/Common/Pokes/PokeResourceBase.cs index e201abf8..4864de07 100644 --- a/src/Kook.Net.Rest/API/Common/Pokes/PokeResourceBase.cs +++ b/src/Kook.Net.Rest/API/Common/Pokes/PokeResourceBase.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -9,4 +9,4 @@ internal class PokeResourceBase : IPokeResource [JsonPropertyName("type")] [JsonConverter(typeof(PokeResourceTypeConverter))] public PokeResourceType Type { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Quote.cs b/src/Kook.Net.Rest/API/Common/Quote.cs index 9dd283f7..1dbb94a7 100644 --- a/src/Kook.Net.Rest/API/Common/Quote.cs +++ b/src/Kook.Net.Rest/API/Common/Quote.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -15,4 +15,4 @@ internal class Quote public DateTimeOffset CreateAt { get; set; } [JsonPropertyName("author")] public User Author { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Reaction.cs b/src/Kook.Net.Rest/API/Common/Reaction.cs index e22fe465..4600a249 100644 --- a/src/Kook.Net.Rest/API/Common/Reaction.cs +++ b/src/Kook.Net.Rest/API/Common/Reaction.cs @@ -7,4 +7,4 @@ internal class Reaction [JsonPropertyName("emoji")] public Emoji Emoji { get; set; } [JsonPropertyName("count")] public int Count { get; set; } [JsonPropertyName("me")] public bool IsMe { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/RecommendInfo.cs b/src/Kook.Net.Rest/API/Common/RecommendInfo.cs index f17da7a9..79566f2f 100644 --- a/src/Kook.Net.Rest/API/Common/RecommendInfo.cs +++ b/src/Kook.Net.Rest/API/Common/RecommendInfo.cs @@ -4,52 +4,52 @@ namespace Kook.API; internal class RecommendInfo { - [JsonPropertyName("guild_id")] + [JsonPropertyName("guild_id")] public ulong GuildId { get; set; } - + [JsonPropertyName("open_id")] public uint OpenId { get; set; } - + [JsonPropertyName("default_channel_id")] public ulong DefaultChannelId { get; set; } - + [JsonPropertyName("name")] public string Name { get; set; } - + [JsonPropertyName("icon")] public string Icon { get; set; } - - [JsonPropertyName("banner")] + + [JsonPropertyName("banner")] public string Banner { get; set; } - - [JsonPropertyName("desc")] + + [JsonPropertyName("desc")] public string Description { get; set; } - - [JsonPropertyName("status")] + + [JsonPropertyName("status")] public int Status { get; set; } - - [JsonPropertyName("tag")] + + [JsonPropertyName("tag")] public string Tag { get; set; } - + [JsonPropertyName("features")] public object[] Features { get; set; } - + [JsonPropertyName("level")] public BoostLevel BoostLevel { get; set; } - - [JsonPropertyName("custom_id")] + + [JsonPropertyName("custom_id")] public string CustomId { get; set; } - + [JsonPropertyName("is_official_partner")] public int IsOfficialPartner { get; set; } - [JsonPropertyName("sort")] + [JsonPropertyName("sort")] public int Sort { get; set; } - - [JsonPropertyName("audit_status")] + + [JsonPropertyName("audit_status")] public int AuditStatus { get; set; } - + [JsonPropertyName("update_day_gap")] public int UpdateDayInterval { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Role.cs b/src/Kook.Net.Rest/API/Common/Role.cs index c2dda975..3b1a6c23 100644 --- a/src/Kook.Net.Rest/API/Common/Role.cs +++ b/src/Kook.Net.Rest/API/Common/Role.cs @@ -12,4 +12,4 @@ internal class Role [JsonPropertyName("mentionable")] public int Mentionable { get; set; } [JsonPropertyName("permissions")] public ulong Permissions { get; set; } [JsonPropertyName("type")] public RoleType? Type { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/RolePermissionOverwrite.cs b/src/Kook.Net.Rest/API/Common/RolePermissionOverwrite.cs index 485f07a3..c41220c1 100644 --- a/src/Kook.Net.Rest/API/Common/RolePermissionOverwrite.cs +++ b/src/Kook.Net.Rest/API/Common/RolePermissionOverwrite.cs @@ -7,4 +7,4 @@ internal class RolePermissionOverwrite [JsonPropertyName("role_id")] public uint RoleId { get; set; } [JsonPropertyName("allow")] public ulong Allow { get; set; } [JsonPropertyName("deny")] public ulong Deny { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/Tag.cs b/src/Kook.Net.Rest/API/Common/Tag.cs index 3d365599..c2a10919 100644 --- a/src/Kook.Net.Rest/API/Common/Tag.cs +++ b/src/Kook.Net.Rest/API/Common/Tag.cs @@ -8,4 +8,4 @@ internal class Tag public string Color { get; set; } [JsonPropertyName("text")] public string Text { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/User.cs b/src/Kook.Net.Rest/API/Common/User.cs index 86a2e7ee..b13c5975 100644 --- a/src/Kook.Net.Rest/API/Common/User.cs +++ b/src/Kook.Net.Rest/API/Common/User.cs @@ -12,11 +12,11 @@ internal class User [JsonPropertyName("online")] public bool Online { get; set; } [JsonPropertyName("os")] public string OperatingSystem { get; set; } [JsonPropertyName("bot")] public bool? Bot { get; set; } - [JsonPropertyName("status")] public int? Status { get; set; } + [JsonPropertyName("status")] public int? Status { get; set; } [JsonPropertyName("avatar")] public string Avatar { get; set; } [JsonPropertyName("vip_avatar")] public string BuffAvatar { get; set; } [JsonPropertyName("is_vip")] public bool? HasBuff { get; set; } [JsonPropertyName("is_ai_reduce_noise")] public bool? IsDenoiseEnabled { get; set; } [JsonPropertyName("tag_info")] public UserTag UserTag { get; set; } [JsonPropertyName("banner")] public string Banner { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/UserChat.cs b/src/Kook.Net.Rest/API/Common/UserChat.cs index 4d643ac9..111e29f8 100644 --- a/src/Kook.Net.Rest/API/Common/UserChat.cs +++ b/src/Kook.Net.Rest/API/Common/UserChat.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -23,4 +23,4 @@ internal class UserChat [JsonPropertyName("is_friend")] public bool? IsFriend { get; set; } [JsonPropertyName("is_blocked")] public bool? IsBlocked { get; set; } [JsonPropertyName("is_target_blocked")] public bool? IsTargetBlocked { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/UserPermissionOverwrite.cs b/src/Kook.Net.Rest/API/Common/UserPermissionOverwrite.cs index 69b32156..14226c49 100644 --- a/src/Kook.Net.Rest/API/Common/UserPermissionOverwrite.cs +++ b/src/Kook.Net.Rest/API/Common/UserPermissionOverwrite.cs @@ -7,4 +7,4 @@ internal class UserPermissionOverwrite [JsonPropertyName("user")] public User User { get; set; } [JsonPropertyName("allow")] public ulong Allow { get; set; } [JsonPropertyName("deny")] public ulong Deny { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Common/UserTag.cs b/src/Kook.Net.Rest/API/Common/UserTag.cs index 5ca674fe..36428276 100644 --- a/src/Kook.Net.Rest/API/Common/UserTag.cs +++ b/src/Kook.Net.Rest/API/Common/UserTag.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API; @@ -11,4 +11,4 @@ internal class UserTag [JsonPropertyName("text")] public string Text { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Net/MultipartFile.cs b/src/Kook.Net.Rest/API/Net/MultipartFile.cs index 2c5a9d94..7a46125f 100644 --- a/src/Kook.Net.Rest/API/Net/MultipartFile.cs +++ b/src/Kook.Net.Rest/API/Net/MultipartFile.cs @@ -14,4 +14,4 @@ public MultipartFile(Stream stream, string filename, string contentType = null) Filename = filename; ContentType = contentType; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/AddOrRemoveRoleParams.cs b/src/Kook.Net.Rest/API/Rest/AddOrRemoveRoleParams.cs index 6d421ada..e891e41d 100644 --- a/src/Kook.Net.Rest/API/Rest/AddOrRemoveRoleParams.cs +++ b/src/Kook.Net.Rest/API/Rest/AddOrRemoveRoleParams.cs @@ -10,6 +10,6 @@ internal class AddOrRemoveRoleParams [JsonPropertyName("user_id")] public ulong UserId { get; set; } - [JsonPropertyName("role_id")] + [JsonPropertyName("role_id")] public uint RoleId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/AddOrRemoveRoleResponsecs.cs b/src/Kook.Net.Rest/API/Rest/AddOrRemoveRoleResponsecs.cs index 16ecb888..c0ec8eac 100644 --- a/src/Kook.Net.Rest/API/Rest/AddOrRemoveRoleResponsecs.cs +++ b/src/Kook.Net.Rest/API/Rest/AddOrRemoveRoleResponsecs.cs @@ -11,4 +11,4 @@ internal class AddOrRemoveRoleResponse public ulong UserId { get; set; } [JsonPropertyName("roles")] public uint[] RoleIds { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/AddReactionParams.cs b/src/Kook.Net.Rest/API/Rest/AddReactionParams.cs index 5217822a..45ad47e2 100644 --- a/src/Kook.Net.Rest/API/Rest/AddReactionParams.cs +++ b/src/Kook.Net.Rest/API/Rest/AddReactionParams.cs @@ -6,7 +6,7 @@ internal class AddReactionParams { [JsonPropertyName("msg_id")] public Guid MessageId { get; set; } - + [JsonPropertyName("emoji")] public string EmojiId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/BeginActivityParams.cs b/src/Kook.Net.Rest/API/Rest/BeginActivityParams.cs index 718bb864..f8c411b2 100644 --- a/src/Kook.Net.Rest/API/Rest/BeginActivityParams.cs +++ b/src/Kook.Net.Rest/API/Rest/BeginActivityParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -13,7 +13,7 @@ public BeginActivityParams(ActivityType activityType) [JsonInclude] [JsonPropertyName("data_type")] public ActivityType ActivityType { get; private set; } - + // Game [JsonPropertyName("id")] public int? Id { get; set; } @@ -22,10 +22,10 @@ public BeginActivityParams(ActivityType activityType) [JsonPropertyName("software")] [JsonConverter(typeof(MusicProviderConverter))] public MusicProvider MusicProvider { get; set; } - + [JsonPropertyName("singer")] public string Signer { get; set; } - + [JsonPropertyName("music_name")] public string MusicName { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/BoostSubscription.cs b/src/Kook.Net.Rest/API/Rest/BoostSubscription.cs index b70026d6..d1ffcedf 100644 --- a/src/Kook.Net.Rest/API/Rest/BoostSubscription.cs +++ b/src/Kook.Net.Rest/API/Rest/BoostSubscription.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; diff --git a/src/Kook.Net.Rest/API/Rest/CreateAssetParams.cs b/src/Kook.Net.Rest/API/Rest/CreateAssetParams.cs index a1f3ae99..4466acc3 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateAssetParams.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateAssetParams.cs @@ -6,7 +6,7 @@ internal class CreateAssetParams { public Stream File { get; set; } public string FileName { get; set; } - + public IReadOnlyDictionary ToDictionary() { var d = new Dictionary @@ -22,4 +22,4 @@ private static string GetFilename(Stream stream) return Path.GetFileName(fileStream.Name); return null; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateAssetResponse.cs b/src/Kook.Net.Rest/API/Rest/CreateAssetResponse.cs index 1e74b23a..a05e8c41 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateAssetResponse.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateAssetResponse.cs @@ -6,4 +6,4 @@ internal class CreateAssetResponse { [JsonPropertyName("url")] public string Url { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateDirectMessageParams.cs b/src/Kook.Net.Rest/API/Rest/CreateDirectMessageParams.cs index 637196a8..ed95b622 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateDirectMessageParams.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateDirectMessageParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -33,11 +33,11 @@ public CreateDirectMessageParams(MessageType messageType, ulong userId, string c UserId = userId; Content = content; } - + public CreateDirectMessageParams(MessageType messageType, Guid chatCode, string content) { Type = messageType; ChatCode = chatCode; Content = content; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateDirectMessageResponse.cs b/src/Kook.Net.Rest/API/Rest/CreateDirectMessageResponse.cs index c988dd61..404a05e6 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateDirectMessageResponse.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateDirectMessageResponse.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -14,4 +14,4 @@ internal class CreateDirectMessageResponse [JsonPropertyName("nonce")] public string Nonce { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateGameParams.cs b/src/Kook.Net.Rest/API/Rest/CreateGameParams.cs index 8b3cad5b..5a203ebe 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateGameParams.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateGameParams.cs @@ -6,12 +6,12 @@ internal class CreateGameParams { [JsonPropertyName("name")] public string Name { get; set; } - + [JsonPropertyName("process_name")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string ProcessName { get; set; } - + [JsonPropertyName("icon")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string Icon { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateGuildBanParams.cs b/src/Kook.Net.Rest/API/Rest/CreateGuildBanParams.cs index e2ef315a..7f4a1885 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateGuildBanParams.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateGuildBanParams.cs @@ -9,11 +9,11 @@ internal class CreateGuildBanParams [JsonPropertyName("target_id")] public ulong UserId { get; set; } - + [JsonPropertyName("remark")] - public string Reason { get; set; } - + public string Reason { get; set; } + [JsonPropertyName("del_msg_days")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public int? DeleteMessageDays { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateGuildChannelParams.cs b/src/Kook.Net.Rest/API/Rest/CreateGuildChannelParams.cs index e70457c6..e48250f1 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateGuildChannelParams.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateGuildChannelParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -14,7 +14,7 @@ internal class CreateGuildChannelParams public ulong? CategoryId { get; set; } [JsonPropertyName("name")] public string Name { get; set; } - [JsonPropertyName("type")] + [JsonPropertyName("type")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ChannelType? Type { get; set; } @@ -26,8 +26,8 @@ internal class CreateGuildChannelParams [JsonConverter(typeof(NullableVoiceQualityConverter))] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public VoiceQuality? VoiceQuality { get; set; } - + [JsonPropertyName("is_category")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public int? IsCategory { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateGuildEmoteParams.cs b/src/Kook.Net.Rest/API/Rest/CreateGuildEmoteParams.cs index 6ca7b096..05a14d38 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateGuildEmoteParams.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateGuildEmoteParams.cs @@ -7,7 +7,7 @@ internal class CreateGuildEmoteParams public string Name { get; set; } public ulong GuildId { get; set; } public Stream File { get; set; } - + public IReadOnlyDictionary ToDictionary() { var d = new Dictionary @@ -17,7 +17,7 @@ public IReadOnlyDictionary ToDictionary() if (Name is not null) d["name"] = $"{Name}"; - + string contentType = "image/png"; if (File is FileStream fileStream) @@ -27,4 +27,4 @@ public IReadOnlyDictionary ToDictionary() return d; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateGuildInviteParams.cs b/src/Kook.Net.Rest/API/Rest/CreateGuildInviteParams.cs index c5eb9dbf..8e195be6 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateGuildInviteParams.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateGuildInviteParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -22,4 +22,4 @@ internal class CreateGuildInviteParams [JsonPropertyName("setting_times")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public InviteMaxUses? MaxUses { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateGuildInviteResponse.cs b/src/Kook.Net.Rest/API/Rest/CreateGuildInviteResponse.cs index 2639a8e5..be86e71b 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateGuildInviteResponse.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateGuildInviteResponse.cs @@ -6,4 +6,4 @@ internal class CreateGuildInviteResponse { [JsonPropertyName("url")] public string Url { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateGuildRoleParams.cs b/src/Kook.Net.Rest/API/Rest/CreateGuildRoleParams.cs index ea629a88..efec3290 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateGuildRoleParams.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateGuildRoleParams.cs @@ -10,4 +10,4 @@ internal class CreateGuildRoleParams [JsonPropertyName("guild_id")] public ulong GuildId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateMessageParams.cs b/src/Kook.Net.Rest/API/Rest/CreateMessageParams.cs index e3b9d684..3974eb34 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateMessageParams.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateMessageParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -24,11 +24,11 @@ internal class CreateMessageParams [JsonConverter(typeof(NullableUInt64Converter))] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ulong? EphemeralUserId { get; set; } - + public CreateMessageParams(MessageType messageType, ulong channelId, string content) { Type = messageType; ChannelId = channelId; Content = content; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateMessageResponse.cs b/src/Kook.Net.Rest/API/Rest/CreateMessageResponse.cs index ce3e32f9..fc177603 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateMessageResponse.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateMessageResponse.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -14,4 +14,4 @@ internal class CreateMessageResponse [JsonPropertyName("nonce")] public string Nonce { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateOrModifyChannelPermissionOverwriteResponse.cs b/src/Kook.Net.Rest/API/Rest/CreateOrModifyChannelPermissionOverwriteResponse.cs index fa2f3608..9d1c2855 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateOrModifyChannelPermissionOverwriteResponse.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateOrModifyChannelPermissionOverwriteResponse.cs @@ -1,14 +1,14 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; internal class CreateOrModifyChannelPermissionOverwriteResponse { - [JsonPropertyName("role_id")] + [JsonPropertyName("role_id")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public uint? RoleId { get; set; } - [JsonPropertyName("user")] + [JsonPropertyName("user")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public User User { get; set; } @@ -17,8 +17,10 @@ public PermissionOverwriteTargetType TargetType { get { - if (RoleId is not null) return PermissionOverwriteTargetType.Role; - if (User is not null) return PermissionOverwriteTargetType.User; + if (RoleId is not null) + return PermissionOverwriteTargetType.Role; + if (User is not null) + return PermissionOverwriteTargetType.User; return PermissionOverwriteTargetType.Unspecified; } } @@ -31,9 +33,9 @@ public PermissionOverwriteTargetType TargetType _ => 0 }; - [JsonPropertyName("allow")] + [JsonPropertyName("allow")] public ulong Allow { get; set; } - - [JsonPropertyName("deny")] + + [JsonPropertyName("deny")] public ulong Deny { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateOrRemoveChannelPermissionOverwriteParams.cs b/src/Kook.Net.Rest/API/Rest/CreateOrRemoveChannelPermissionOverwriteParams.cs index d6174deb..d2a3a628 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateOrRemoveChannelPermissionOverwriteParams.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateOrRemoveChannelPermissionOverwriteParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -11,7 +11,7 @@ internal class CreateOrRemoveChannelPermissionOverwriteParams [JsonPropertyName("type")] [JsonConverter(typeof(PermissionOverwriteTargetTypeConverter))] public PermissionOverwriteTargetType TargetType { get; set; } - + [JsonPropertyName("value")] public ulong TargetId { get; set; } @@ -21,4 +21,4 @@ public CreateOrRemoveChannelPermissionOverwriteParams(ulong channelId, Permissio TargetType = targetType; TargetId = targetId; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateOrRemoveGuildMuteDeafParams.cs b/src/Kook.Net.Rest/API/Rest/CreateOrRemoveGuildMuteDeafParams.cs index acaefac2..16a173ac 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateOrRemoveGuildMuteDeafParams.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateOrRemoveGuildMuteDeafParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -7,10 +7,10 @@ internal class CreateOrRemoveGuildMuteDeafParams { [JsonPropertyName("guild_id")] public ulong GuildId { get; set; } - + [JsonPropertyName("target_id")] public ulong UserId { get; set; } [JsonPropertyName("type")] public MuteOrDeafType Type { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/CreateUserChatParams.cs b/src/Kook.Net.Rest/API/Rest/CreateUserChatParams.cs index 482f5af1..e44ef43e 100644 --- a/src/Kook.Net.Rest/API/Rest/CreateUserChatParams.cs +++ b/src/Kook.Net.Rest/API/Rest/CreateUserChatParams.cs @@ -7,5 +7,5 @@ internal class CreateUserChatParams [JsonPropertyName("target_id")] public ulong UserId { get; set; } - public static implicit operator CreateUserChatParams(ulong userId) => new() {UserId = userId}; -} \ No newline at end of file + public static implicit operator CreateUserChatParams(ulong userId) => new() { UserId = userId }; +} diff --git a/src/Kook.Net.Rest/API/Rest/DeleteDirectMessageParams.cs b/src/Kook.Net.Rest/API/Rest/DeleteDirectMessageParams.cs index 6ffa6fd8..092918d3 100644 --- a/src/Kook.Net.Rest/API/Rest/DeleteDirectMessageParams.cs +++ b/src/Kook.Net.Rest/API/Rest/DeleteDirectMessageParams.cs @@ -6,6 +6,6 @@ internal class DeleteDirectMessageParams { [JsonPropertyName("msg_id")] public Guid MessageId { get; set; } - - public static implicit operator DeleteDirectMessageParams(Guid messageId) => new() {MessageId = messageId}; -} \ No newline at end of file + + public static implicit operator DeleteDirectMessageParams(Guid messageId) => new() { MessageId = messageId }; +} diff --git a/src/Kook.Net.Rest/API/Rest/DeleteGameParams.cs b/src/Kook.Net.Rest/API/Rest/DeleteGameParams.cs index 6b2ebb38..5f360b2f 100644 --- a/src/Kook.Net.Rest/API/Rest/DeleteGameParams.cs +++ b/src/Kook.Net.Rest/API/Rest/DeleteGameParams.cs @@ -6,6 +6,6 @@ internal class DeleteGameParams { [JsonPropertyName("id")] public int Id { get; set; } - - public static implicit operator DeleteGameParams(int id) => new() {Id = id}; -} \ No newline at end of file + + public static implicit operator DeleteGameParams(int id) => new() { Id = id }; +} diff --git a/src/Kook.Net.Rest/API/Rest/DeleteGuildChannelParams.cs b/src/Kook.Net.Rest/API/Rest/DeleteGuildChannelParams.cs index fe2ef301..a40c9f97 100644 --- a/src/Kook.Net.Rest/API/Rest/DeleteGuildChannelParams.cs +++ b/src/Kook.Net.Rest/API/Rest/DeleteGuildChannelParams.cs @@ -7,5 +7,5 @@ internal class DeleteGuildChannelParams [JsonPropertyName("channel_id")] public ulong ChannelId { get; set; } - public static implicit operator DeleteGuildChannelParams(ulong channelId) => new() {ChannelId = channelId}; -} \ No newline at end of file + public static implicit operator DeleteGuildChannelParams(ulong channelId) => new() { ChannelId = channelId }; +} diff --git a/src/Kook.Net.Rest/API/Rest/DeleteGuildEmoteParams.cs b/src/Kook.Net.Rest/API/Rest/DeleteGuildEmoteParams.cs index 2b0532b4..74794719 100644 --- a/src/Kook.Net.Rest/API/Rest/DeleteGuildEmoteParams.cs +++ b/src/Kook.Net.Rest/API/Rest/DeleteGuildEmoteParams.cs @@ -6,5 +6,5 @@ internal class DeleteGuildEmoteParams { [JsonPropertyName("id")] public string Id { get; set; } - public static implicit operator DeleteGuildEmoteParams(string id) => new() {Id = id}; -} \ No newline at end of file + public static implicit operator DeleteGuildEmoteParams(string id) => new() { Id = id }; +} diff --git a/src/Kook.Net.Rest/API/Rest/DeleteGuildInviteParams.cs b/src/Kook.Net.Rest/API/Rest/DeleteGuildInviteParams.cs index cf9806e2..d4b760b7 100644 --- a/src/Kook.Net.Rest/API/Rest/DeleteGuildInviteParams.cs +++ b/src/Kook.Net.Rest/API/Rest/DeleteGuildInviteParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -7,7 +7,7 @@ internal class DeleteGuildInviteParams { [JsonPropertyName("url_code")] public string UrlCode { get; set; } - + [JsonPropertyName("guild_id")] [JsonConverter(typeof(NullableUInt64Converter))] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -17,4 +17,4 @@ internal class DeleteGuildInviteParams [JsonConverter(typeof(NullableUInt64Converter))] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ulong? ChannelId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/DeleteGuildRoleParams.cs b/src/Kook.Net.Rest/API/Rest/DeleteGuildRoleParams.cs index 1a8f41bd..b0786eb0 100644 --- a/src/Kook.Net.Rest/API/Rest/DeleteGuildRoleParams.cs +++ b/src/Kook.Net.Rest/API/Rest/DeleteGuildRoleParams.cs @@ -8,4 +8,4 @@ internal class DeleteGuildRoleParams public ulong GuildId { get; set; } [JsonPropertyName("role_id")] public uint Id { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/DeleteMessageParams.cs b/src/Kook.Net.Rest/API/Rest/DeleteMessageParams.cs index a0dc1f13..35a5572c 100644 --- a/src/Kook.Net.Rest/API/Rest/DeleteMessageParams.cs +++ b/src/Kook.Net.Rest/API/Rest/DeleteMessageParams.cs @@ -6,6 +6,6 @@ internal class DeleteMessageParams { [JsonPropertyName("msg_id")] public Guid MessageId { get; set; } - - public static implicit operator DeleteMessageParams(Guid messageId) => new() {MessageId = messageId}; -} \ No newline at end of file + + public static implicit operator DeleteMessageParams(Guid messageId) => new() { MessageId = messageId }; +} diff --git a/src/Kook.Net.Rest/API/Rest/DeleteUserChatParams.cs b/src/Kook.Net.Rest/API/Rest/DeleteUserChatParams.cs index 0c7852d4..dc4c2c77 100644 --- a/src/Kook.Net.Rest/API/Rest/DeleteUserChatParams.cs +++ b/src/Kook.Net.Rest/API/Rest/DeleteUserChatParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -9,5 +9,5 @@ internal class DeleteUserChatParams [JsonConverter(typeof(ChatCodeConverter))] public Guid ChatCode { get; set; } - public static implicit operator DeleteUserChatParams(Guid chatCode) => new() {ChatCode = chatCode}; -} \ No newline at end of file + public static implicit operator DeleteUserChatParams(Guid chatCode) => new() { ChatCode = chatCode }; +} diff --git a/src/Kook.Net.Rest/API/Rest/EndGameActivityParams.cs b/src/Kook.Net.Rest/API/Rest/EndGameActivityParams.cs index 34944686..863a3167 100644 --- a/src/Kook.Net.Rest/API/Rest/EndGameActivityParams.cs +++ b/src/Kook.Net.Rest/API/Rest/EndGameActivityParams.cs @@ -8,8 +8,8 @@ public EndGameActivityParams(ActivityType activityType) { ActivityType = activityType; } - + [JsonInclude] [JsonPropertyName("data_type")] public ActivityType ActivityType { get; private set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/ExtendedGuild.cs b/src/Kook.Net.Rest/API/Rest/ExtendedGuild.cs index 5c2a40c8..e211d801 100644 --- a/src/Kook.Net.Rest/API/Rest/ExtendedGuild.cs +++ b/src/Kook.Net.Rest/API/Rest/ExtendedGuild.cs @@ -9,7 +9,7 @@ internal class ExtendedGuild : Guild [JsonPropertyName("boost_num")] public int BoostSubscriptionCount { get; set; } - + [JsonPropertyName("buffer_boost_num")] public int BufferBoostSubscriptionCount { get; set; } @@ -24,4 +24,4 @@ internal class ExtendedGuild : Guild [JsonPropertyName("recommend_info")] public RecommendInfo RecommendInfo { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/GetBotGatewayResponse.cs b/src/Kook.Net.Rest/API/Rest/GetBotGatewayResponse.cs index e60a5b69..e6603efc 100644 --- a/src/Kook.Net.Rest/API/Rest/GetBotGatewayResponse.cs +++ b/src/Kook.Net.Rest/API/Rest/GetBotGatewayResponse.cs @@ -6,4 +6,4 @@ internal class GetBotGatewayResponse { [JsonPropertyName("url")] public string Url { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/GetChannelPermissionOverwritesResponse.cs b/src/Kook.Net.Rest/API/Rest/GetChannelPermissionOverwritesResponse.cs index 7812027c..907eeddd 100644 --- a/src/Kook.Net.Rest/API/Rest/GetChannelPermissionOverwritesResponse.cs +++ b/src/Kook.Net.Rest/API/Rest/GetChannelPermissionOverwritesResponse.cs @@ -1,17 +1,17 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; internal class GetChannelPermissionOverwritesResponse -{ +{ [JsonPropertyName("permission_overwrites")] public RolePermissionOverwrite[] RolePermissionOverwrites { get; set; } - [JsonPropertyName("permission_users")] + [JsonPropertyName("permission_users")] public UserPermissionOverwrite[] UserPermissionOverwrites { get; set; } - [JsonPropertyName("permission_sync")] + [JsonPropertyName("permission_sync")] [JsonConverter(typeof(NumberBooleanConverter))] public bool PermissionSync { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/GetGuildMemberCountResponse.cs b/src/Kook.Net.Rest/API/Rest/GetGuildMemberCountResponse.cs index 1d46f147..0e4e36b3 100644 --- a/src/Kook.Net.Rest/API/Rest/GetGuildMemberCountResponse.cs +++ b/src/Kook.Net.Rest/API/Rest/GetGuildMemberCountResponse.cs @@ -10,4 +10,4 @@ internal class GetGuildMemberCountResponse public int OnlineCount { get; set; } [JsonPropertyName("offline_count")] public int OfflineCount { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/GetGuildMuteDeafListResponse.cs b/src/Kook.Net.Rest/API/Rest/GetGuildMuteDeafListResponse.cs index bf08c49e..da3dadea 100644 --- a/src/Kook.Net.Rest/API/Rest/GetGuildMuteDeafListResponse.cs +++ b/src/Kook.Net.Rest/API/Rest/GetGuildMuteDeafListResponse.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -7,7 +7,7 @@ internal class GetGuildMuteDeafListResponse { [JsonPropertyName("mic")] public MuteOrDeafDetail Muted { get; set; } - + [JsonPropertyName("headset")] public MuteOrDeafDetail Deafened { get; set; } } @@ -17,6 +17,6 @@ internal class MuteOrDeafDetail [JsonPropertyName("type")] public MuteOrDeafType Type { get; set; } - [JsonPropertyName("user_ids")] + [JsonPropertyName("user_ids")] public ulong[] UserIds { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/GetVoiceGatewayResponse.cs b/src/Kook.Net.Rest/API/Rest/GetVoiceGatewayResponse.cs index f8e08ec6..5f284dbd 100644 --- a/src/Kook.Net.Rest/API/Rest/GetVoiceGatewayResponse.cs +++ b/src/Kook.Net.Rest/API/Rest/GetVoiceGatewayResponse.cs @@ -6,4 +6,4 @@ internal class GetVoiceGatewayResponse { [JsonPropertyName("gateway_url")] public string Url { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/GuildMember.cs b/src/Kook.Net.Rest/API/Rest/GuildMember.cs index 13e977f0..ea210e1d 100644 --- a/src/Kook.Net.Rest/API/Rest/GuildMember.cs +++ b/src/Kook.Net.Rest/API/Rest/GuildMember.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -27,7 +27,7 @@ internal class GuildMember : User [JsonPropertyName("desc")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string Description { get; set; } - + [JsonPropertyName("abbr")] public string Abbreviation { get; set; } } @@ -37,4 +37,4 @@ internal class HoistInfo [JsonPropertyName("role_id")] public uint RoleId { get; set; } [JsonPropertyName("name")] public string Name { get; set; } [JsonPropertyName("color")] public uint Color { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/KickOutGuildMemberParams.cs b/src/Kook.Net.Rest/API/Rest/KickOutGuildMemberParams.cs index 77f2f849..8aff219d 100644 --- a/src/Kook.Net.Rest/API/Rest/KickOutGuildMemberParams.cs +++ b/src/Kook.Net.Rest/API/Rest/KickOutGuildMemberParams.cs @@ -6,7 +6,7 @@ internal class KickOutGuildMemberParams { [JsonPropertyName("guild_id")] public ulong GuildId { get; set; } - + [JsonPropertyName("target_id")] public ulong UserId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/LeaveGuildParams.cs b/src/Kook.Net.Rest/API/Rest/LeaveGuildParams.cs index 77fab9b2..acf95ee2 100644 --- a/src/Kook.Net.Rest/API/Rest/LeaveGuildParams.cs +++ b/src/Kook.Net.Rest/API/Rest/LeaveGuildParams.cs @@ -7,5 +7,5 @@ internal class LeaveGuildParams [JsonPropertyName("guild_id")] public ulong GuildId { get; set; } - public static implicit operator LeaveGuildParams(ulong guildId) => new() {GuildId = guildId}; -} \ No newline at end of file + public static implicit operator LeaveGuildParams(ulong guildId) => new() { GuildId = guildId }; +} diff --git a/src/Kook.Net.Rest/API/Rest/ModifyChannelPermissionOverwriteParams.cs b/src/Kook.Net.Rest/API/Rest/ModifyChannelPermissionOverwriteParams.cs index 6372676d..3430b24d 100644 --- a/src/Kook.Net.Rest/API/Rest/ModifyChannelPermissionOverwriteParams.cs +++ b/src/Kook.Net.Rest/API/Rest/ModifyChannelPermissionOverwriteParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -15,12 +15,12 @@ internal class ModifyChannelPermissionOverwriteParams [JsonPropertyName("value")] public ulong TargetId { get; set; } - [JsonPropertyName("allow")] + [JsonPropertyName("allow")] [JsonConverter(typeof(NullableUInt64Converter))] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ulong? Allow { get; set; } - - [JsonPropertyName("deny")] + + [JsonPropertyName("deny")] [JsonConverter(typeof(NullableUInt64Converter))] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ulong? Deny { get; set; } @@ -33,4 +33,4 @@ public ModifyChannelPermissionOverwriteParams(ulong channelId, PermissionOverwri Allow = allow; Deny = deny; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/ModifyDirectMessageParams.cs b/src/Kook.Net.Rest/API/Rest/ModifyDirectMessageParams.cs index 4ae5d13a..fd783c22 100644 --- a/src/Kook.Net.Rest/API/Rest/ModifyDirectMessageParams.cs +++ b/src/Kook.Net.Rest/API/Rest/ModifyDirectMessageParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -18,4 +18,4 @@ public ModifyDirectMessageParams(Guid messageId, string content) MessageId = messageId; Content = content; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/ModifyGameParams.cs b/src/Kook.Net.Rest/API/Rest/ModifyGameParams.cs index 74a92a31..16c07ec7 100644 --- a/src/Kook.Net.Rest/API/Rest/ModifyGameParams.cs +++ b/src/Kook.Net.Rest/API/Rest/ModifyGameParams.cs @@ -6,12 +6,12 @@ internal class ModifyGameParams { [JsonPropertyName("id")] public int Id { get; set; } - + [JsonPropertyName("name")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string Name { get; set; } - + [JsonPropertyName("icon")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string Icon { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/ModifyGuildChannelParams.cs b/src/Kook.Net.Rest/API/Rest/ModifyGuildChannelParams.cs index 6a5f49cc..2dfa95b2 100644 --- a/src/Kook.Net.Rest/API/Rest/ModifyGuildChannelParams.cs +++ b/src/Kook.Net.Rest/API/Rest/ModifyGuildChannelParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -7,17 +7,17 @@ internal class ModifyGuildChannelParams { [JsonPropertyName("channel_id")] public ulong ChannelId { get; set; } - - [JsonPropertyName("name")] + + [JsonPropertyName("name")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string Name { get; set; } - - [JsonPropertyName("level")] + + [JsonPropertyName("level")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public int? Position { get; set; } - + [JsonPropertyName("parent_id")] [JsonConverter(typeof(NullableUInt64Converter))] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ulong? CategoryId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/ModifyGuildEmoteParams.cs b/src/Kook.Net.Rest/API/Rest/ModifyGuildEmoteParams.cs index 31cfad13..de4505a3 100644 --- a/src/Kook.Net.Rest/API/Rest/ModifyGuildEmoteParams.cs +++ b/src/Kook.Net.Rest/API/Rest/ModifyGuildEmoteParams.cs @@ -6,7 +6,7 @@ internal class ModifyGuildEmoteParams { [JsonPropertyName("id")] public string Id { get; set; } - + [JsonPropertyName("name")] public string Name { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/ModifyGuildMemberNicknameParams.cs b/src/Kook.Net.Rest/API/Rest/ModifyGuildMemberNicknameParams.cs index f44b800f..9a648932 100644 --- a/src/Kook.Net.Rest/API/Rest/ModifyGuildMemberNicknameParams.cs +++ b/src/Kook.Net.Rest/API/Rest/ModifyGuildMemberNicknameParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -16,4 +16,4 @@ internal class ModifyGuildMemberNicknameParams [JsonConverter(typeof(NullableUInt64Converter))] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ulong? UserId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/ModifyGuildRoleParams.cs b/src/Kook.Net.Rest/API/Rest/ModifyGuildRoleParams.cs index fdeaba8d..3589a333 100644 --- a/src/Kook.Net.Rest/API/Rest/ModifyGuildRoleParams.cs +++ b/src/Kook.Net.Rest/API/Rest/ModifyGuildRoleParams.cs @@ -7,7 +7,7 @@ internal class ModifyGuildRoleParams [JsonPropertyName("guild_id")] public ulong GuildId { get; set; } - [JsonPropertyName("role_id")] + [JsonPropertyName("role_id")] public uint RoleId { get; set; } [JsonPropertyName("name")] @@ -29,4 +29,4 @@ internal class ModifyGuildRoleParams [JsonPropertyName("permissions")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public ulong? Permissions { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/ModifyMessageParams.cs b/src/Kook.Net.Rest/API/Rest/ModifyMessageParams.cs index d8d77651..5693358b 100644 --- a/src/Kook.Net.Rest/API/Rest/ModifyMessageParams.cs +++ b/src/Kook.Net.Rest/API/Rest/ModifyMessageParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -23,4 +23,4 @@ public ModifyMessageParams(Guid messageId, string content) MessageId = messageId; Content = content; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/ModifyTextChannelParams.cs b/src/Kook.Net.Rest/API/Rest/ModifyTextChannelParams.cs index c7d90f2e..fb1624c1 100644 --- a/src/Kook.Net.Rest/API/Rest/ModifyTextChannelParams.cs +++ b/src/Kook.Net.Rest/API/Rest/ModifyTextChannelParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -7,6 +7,6 @@ internal class ModifyTextChannelParams : ModifyGuildChannelParams { [JsonPropertyName("topic")] public string Topic { get; set; } - [JsonPropertyName("slow_mode")] + [JsonPropertyName("slow_mode")] public int? SlowModeInterval { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/ModifyVoiceChannelParams.cs b/src/Kook.Net.Rest/API/Rest/ModifyVoiceChannelParams.cs index 08bdc160..6264f8cc 100644 --- a/src/Kook.Net.Rest/API/Rest/ModifyVoiceChannelParams.cs +++ b/src/Kook.Net.Rest/API/Rest/ModifyVoiceChannelParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -10,7 +10,7 @@ internal class ModifyVoiceChannelParams : ModifyGuildChannelParams [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public VoiceQuality? VoiceQuality { get; set; } - [JsonPropertyName("limit_amount")] + [JsonPropertyName("limit_amount")] public int? UserLimit { get; set; } [JsonPropertyName("password")] diff --git a/src/Kook.Net.Rest/API/Rest/MoveUsersParams.cs b/src/Kook.Net.Rest/API/Rest/MoveUsersParams.cs index 58223a7b..c2da0847 100644 --- a/src/Kook.Net.Rest/API/Rest/MoveUsersParams.cs +++ b/src/Kook.Net.Rest/API/Rest/MoveUsersParams.cs @@ -6,7 +6,7 @@ internal class MoveUsersParams { [JsonPropertyName("target_id")] public ulong ChannelId { get; set; } - + [JsonPropertyName("user_ids")] public ulong[] UserIds { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/MuteOrDeafType.cs b/src/Kook.Net.Rest/API/Rest/MuteOrDeafType.cs index 6dc1925d..ab738aef 100644 --- a/src/Kook.Net.Rest/API/Rest/MuteOrDeafType.cs +++ b/src/Kook.Net.Rest/API/Rest/MuteOrDeafType.cs @@ -4,4 +4,4 @@ internal enum MuteOrDeafType { Mute = 1, Deaf = 2 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/PagedResponseBase.cs b/src/Kook.Net.Rest/API/Rest/PagedResponseBase.cs index d3b7a6ce..dc869cac 100644 --- a/src/Kook.Net.Rest/API/Rest/PagedResponseBase.cs +++ b/src/Kook.Net.Rest/API/Rest/PagedResponseBase.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -27,13 +27,13 @@ public PageMeta(int page = 1, int pageSize = 100) [JsonPropertyName("page")] public int Page { get; set; } - + [JsonPropertyName("page_total")] public int PageTotal { get; set; } - + [JsonPropertyName("page_size")] public int PageSize { get; set; } - + [JsonPropertyName("total")] public int Total { get; set; } @@ -44,4 +44,4 @@ internal struct PageSortInfo { public string SortKey { get; set; } public SortMode SortMode { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/PermissionOverwriteTargetType.cs b/src/Kook.Net.Rest/API/Rest/PermissionOverwriteTargetType.cs index 95840ceb..ac5f56f5 100644 --- a/src/Kook.Net.Rest/API/Rest/PermissionOverwriteTargetType.cs +++ b/src/Kook.Net.Rest/API/Rest/PermissionOverwriteTargetType.cs @@ -5,4 +5,4 @@ internal enum PermissionOverwriteTargetType Unspecified, Role, User -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/QueryMessagesResponse.cs b/src/Kook.Net.Rest/API/Rest/QueryMessagesResponse.cs index 23d24dee..a2799d65 100644 --- a/src/Kook.Net.Rest/API/Rest/QueryMessagesResponse.cs +++ b/src/Kook.Net.Rest/API/Rest/QueryMessagesResponse.cs @@ -6,4 +6,4 @@ internal class QueryMessagesResponse { [JsonPropertyName("items")] public Message[] Items { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/QueryUserChatMessagesResponse.cs b/src/Kook.Net.Rest/API/Rest/QueryUserChatMessagesResponse.cs index 089c472e..aa548493 100644 --- a/src/Kook.Net.Rest/API/Rest/QueryUserChatMessagesResponse.cs +++ b/src/Kook.Net.Rest/API/Rest/QueryUserChatMessagesResponse.cs @@ -6,4 +6,4 @@ internal class QueryUserChatMessagesResponse { [JsonPropertyName("items")] public DirectMessage[] Items { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/ReactionUserResponse.cs b/src/Kook.Net.Rest/API/Rest/ReactionUserResponse.cs index bb40b612..0ad08f70 100644 --- a/src/Kook.Net.Rest/API/Rest/ReactionUserResponse.cs +++ b/src/Kook.Net.Rest/API/Rest/ReactionUserResponse.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -8,4 +8,4 @@ internal class ReactionUserResponse : User [JsonPropertyName("reaction_time")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset ReactionTime { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/RemoveGuildBanParams.cs b/src/Kook.Net.Rest/API/Rest/RemoveGuildBanParams.cs index 87b146a5..a34c9377 100644 --- a/src/Kook.Net.Rest/API/Rest/RemoveGuildBanParams.cs +++ b/src/Kook.Net.Rest/API/Rest/RemoveGuildBanParams.cs @@ -9,4 +9,4 @@ internal class RemoveGuildBanParams [JsonPropertyName("target_id")] public ulong UserId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/RemoveReactionParams.cs b/src/Kook.Net.Rest/API/Rest/RemoveReactionParams.cs index 33581f8e..c6d8d7e6 100644 --- a/src/Kook.Net.Rest/API/Rest/RemoveReactionParams.cs +++ b/src/Kook.Net.Rest/API/Rest/RemoveReactionParams.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Rest; @@ -7,7 +7,7 @@ internal class RemoveReactionParams { [JsonPropertyName("msg_id")] public Guid MessageId { get; set; } - + [JsonPropertyName("emoji")] public string EmojiId { get; set; } diff --git a/src/Kook.Net.Rest/API/Rest/RestResponseBase.cs b/src/Kook.Net.Rest/API/Rest/RestResponseBase.cs index 4a3e6f9c..64a3c3e6 100644 --- a/src/Kook.Net.Rest/API/Rest/RestResponseBase.cs +++ b/src/Kook.Net.Rest/API/Rest/RestResponseBase.cs @@ -6,10 +6,10 @@ internal class RestResponseBase { [JsonPropertyName("code")] public KookErrorCode Code { get; set; } - + [JsonPropertyName("message")] public string Message { get; set; } - + [JsonPropertyName("data")] public object Data { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/RichGuild.cs b/src/Kook.Net.Rest/API/Rest/RichGuild.cs index 1c223d91..0d0697f7 100644 --- a/src/Kook.Net.Rest/API/Rest/RichGuild.cs +++ b/src/Kook.Net.Rest/API/Rest/RichGuild.cs @@ -6,7 +6,7 @@ internal class RichGuild : ExtendedGuild { [JsonPropertyName("user_id")] public new ulong OwnerId { get; set; } - - [JsonPropertyName("emojis")] + + [JsonPropertyName("emojis")] public Emoji[] Emojis { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/SelfUser.cs b/src/Kook.Net.Rest/API/Rest/SelfUser.cs index a5f00a30..5d46b274 100644 --- a/src/Kook.Net.Rest/API/Rest/SelfUser.cs +++ b/src/Kook.Net.Rest/API/Rest/SelfUser.cs @@ -8,4 +8,4 @@ internal class SelfUser : User [JsonPropertyName("MobilePrefix")] public string MobilePrefix { get; set; } [JsonPropertyName("Mobile")] public string Mobile { get; set; } [JsonPropertyName("InvitedCount")] public int? InvitedCount { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/SortMode.cs b/src/Kook.Net.Rest/API/Rest/SortMode.cs index 6e903a90..b9b6284f 100644 --- a/src/Kook.Net.Rest/API/Rest/SortMode.cs +++ b/src/Kook.Net.Rest/API/Rest/SortMode.cs @@ -5,4 +5,4 @@ internal enum SortMode Ascending = 1, Unspecified = 0, Descending = -1 -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/API/Rest/UpdateIntimacyValueParams.cs b/src/Kook.Net.Rest/API/Rest/UpdateIntimacyValueParams.cs index 0764bf30..821afbba 100644 --- a/src/Kook.Net.Rest/API/Rest/UpdateIntimacyValueParams.cs +++ b/src/Kook.Net.Rest/API/Rest/UpdateIntimacyValueParams.cs @@ -13,4 +13,4 @@ internal class UpdateIntimacyValueParams [JsonPropertyName("img_id")] public uint ImageId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/AssemblyInfo.cs b/src/Kook.Net.Rest/AssemblyInfo.cs index 9c2e1e7a..665a7ba7 100644 --- a/src/Kook.Net.Rest/AssemblyInfo.cs +++ b/src/Kook.Net.Rest/AssemblyInfo.cs @@ -3,4 +3,4 @@ [assembly: InternalsVisibleTo("Kook.Net.WebSocket")] [assembly: InternalsVisibleTo("Kook.Net.Experimental")] [assembly: InternalsVisibleTo("Kook.Net.Tests.Unit")] -[assembly: InternalsVisibleTo("Kook.Net.Tests.Integration")] \ No newline at end of file +[assembly: InternalsVisibleTo("Kook.Net.Tests.Integration")] diff --git a/src/Kook.Net.Rest/BaseKookClient.cs b/src/Kook.Net.Rest/BaseKookClient.cs index 8ffaddb9..597831ac 100644 --- a/src/Kook.Net.Rest/BaseKookClient.cs +++ b/src/Kook.Net.Rest/BaseKookClient.cs @@ -1,5 +1,5 @@ -using System.Collections.Immutable; using Kook.Logging; +using System.Collections.Immutable; namespace Kook.Rest; @@ -12,13 +12,13 @@ public abstract class BaseKookClient : IKookClient private readonly AsyncEvent> _loggedInEvent = new AsyncEvent>(); public event Func LoggedOut { add => _loggedOutEvent.Add(value); remove => _loggedOutEvent.Remove(value); } private readonly AsyncEvent> _loggedOutEvent = new AsyncEvent>(); - + internal readonly Logger _restLogger; private readonly SemaphoreSlim _stateLock; private bool _isFirstLogin, _isDisposed; - + internal API.KookRestApiClient ApiClient { get; } - + internal LogManager LogManager { get; } /// /// Gets the login state of the client. @@ -30,17 +30,17 @@ public abstract class BaseKookClient : IKookClient public ISelfUser CurrentUser { get; protected set; } /// public TokenType TokenType => ApiClient.AuthTokenType; - + internal BaseKookClient(KookRestConfig config, API.KookRestApiClient client) { ApiClient = client; LogManager = new LogManager(config.LogLevel); LogManager.Message += async msg => await _logEvent.InvokeAsync(msg).ConfigureAwait(false); - + _stateLock = new SemaphoreSlim(1, 1); _restLogger = LogManager.CreateLogger("Rest"); _isFirstLogin = config.DisplayInitialLog; - + ApiClient.RequestQueue.RateLimitTriggered += async (id, info, endpoint) => { if (info == null) @@ -50,7 +50,7 @@ internal BaseKookClient(KookRestConfig config, API.KookRestApiClient client) }; ApiClient.SentRequest += async (method, endpoint, millis) => await _restLogger.VerboseAsync($"{method} {endpoint}: {millis} ms").ConfigureAwait(false); } - + internal virtual void Dispose(bool disposing) { if (!_isDisposed) @@ -72,7 +72,7 @@ public async Task LoginAsync(TokenType tokenType, string token, bool validateTok } finally { _stateLock.Release(); } } - + internal virtual async Task LoginInternalAsync(TokenType tokenType, string token, bool validateToken) { if (_isFirstLogin) @@ -116,7 +116,7 @@ internal virtual async Task LoginInternalAsync(TokenType tokenType, string token } internal virtual Task OnLoginAsync(TokenType tokenType, string token) => Task.Delay(0); - + public async Task LogoutAsync() { await _stateLock.WaitAsync().ConfigureAwait(false); @@ -129,8 +129,9 @@ public async Task LogoutAsync() internal virtual async Task LogoutInternalAsync() { await ApiClient.GoOfflineAsync(); - - if (LoginState == LoginState.LoggedOut) return; + + if (LoginState == LoginState.LoggedOut) + return; LoginState = LoginState.LoggingOut; await ApiClient.LogoutAsync().ConfigureAwait(false); @@ -143,14 +144,14 @@ internal virtual async Task LogoutInternalAsync() } internal virtual Task OnLogoutAsync() => Task.Delay(0); - + #endregion #region IKookClient - + /// ConnectionState IKookClient.ConnectionState => ConnectionState.Disconnected; - + /// ISelfUser IKookClient.CurrentUser => CurrentUser; @@ -172,13 +173,13 @@ Task> IKookClient.GetDMChannelsAsync(CacheMode m /// Task IKookClient.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult(null); - + /// Task IKookClient.StartAsync() => Task.Delay(0); /// Task IKookClient.StopAsync() => Task.Delay(0); - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/ClientHelper.cs b/src/Kook.Net.Rest/ClientHelper.cs index 0d405ee3..441986e5 100644 --- a/src/Kook.Net.Rest/ClientHelper.cs +++ b/src/Kook.Net.Rest/ClientHelper.cs @@ -1,5 +1,5 @@ -using System.Collections.Immutable; using Kook.API.Rest; +using System.Collections.Immutable; namespace Kook.Rest; @@ -38,7 +38,7 @@ public static async Task GetChannelAsync(BaseKookClient client, return RestChannel.Create(client, model); return null; } - + public static async Task GetDMChannelAsync(BaseKookClient client, Guid chatCode, RequestOptions options) { @@ -47,7 +47,7 @@ public static async Task GetDMChannelAsync(BaseKookClient client, return RestDMChannel.Create(client, model); return null; } - + public static async Task> GetDMChannelsAsync(BaseKookClient client, RequestOptions options) { var model = await client.ApiClient.GetUserChatsAsync(options: options).FlattenAsync().ConfigureAwait(false); @@ -55,7 +55,7 @@ public static async Task> GetDMChannelsAsync( return model.Select(x => RestDMChannel.Create(client, x)).ToImmutableArray(); return null; } - + public static async Task GetUserAsync(BaseKookClient client, ulong id, RequestOptions options) { @@ -64,7 +64,7 @@ public static async Task GetUserAsync(BaseKookClient client, return RestUser.Create(client, model); return null; } - + public static async Task GetGuildMemberAsync(BaseKookClient client, ulong guildId, ulong id, RequestOptions options) { @@ -87,10 +87,10 @@ public static async Task MoveUsersAsync(BaseKookClient client, IEnumerable x.Id).ToArray() }; await client.ApiClient.MoveUsersAsync(args, options).ConfigureAwait(false); - } + } public static async Task CreateAssetAsync(BaseKookClient client, Stream stream, string fileName, RequestOptions options) { - var model = await client.ApiClient.CreateAssetAsync(new CreateAssetParams {File = stream, FileName = fileName}, options); + var model = await client.ApiClient.CreateAssetAsync(new CreateAssetParams { File = stream, FileName = fileName }, options); if (model != null) return model.Url; return null; @@ -113,12 +113,12 @@ public static async Task CreateGameAsync(BaseKookClient client, string var model = await client.ApiClient.CreateGameAsync(args, options).ConfigureAwait(false); return RestGame.Create(client, model); } - + public static async Task DeleteGameAsync(BaseKookClient client, int id, RequestOptions options) { await client.ApiClient.DeleteGameAsync(id, options).ConfigureAwait(false); } - + public static async Task AddRoleAsync(BaseKookClient client, ulong guildId, ulong userId, uint roleId, RequestOptions options = null) { AddOrRemoveRoleParams args = new() @@ -140,4 +140,4 @@ public static async Task RemoveRoleAsync(BaseKookClient client, ulong guildId, u }; await client.ApiClient.RemoveRoleAsync(args, options).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Channels/ChannelHelper.cs b/src/Kook.Net.Rest/Entities/Channels/ChannelHelper.cs index 13b65d2b..66efd7b7 100644 --- a/src/Kook.Net.Rest/Entities/Channels/ChannelHelper.cs +++ b/src/Kook.Net.Rest/Entities/Channels/ChannelHelper.cs @@ -1,7 +1,7 @@ -using System.Collections.Immutable; using Kook.API; using Kook.API.Rest; using Kook.Utils; +using System.Collections.Immutable; using Model = Kook.API.Channel; namespace Kook.Rest; @@ -213,7 +213,7 @@ public static async Task> SendMessageAsync(IMessag EphemeralUserId = ephemeralUser?.Id }; CreateMessageResponse model = await client.ApiClient.CreateMessageAsync(args, options).ConfigureAwait(false); - return new Cacheable(null, model.MessageId, false, + return new Cacheable(null, model.MessageId, false, async () => await channel.GetMessageAsync(model.MessageId) as IUserMessage); } @@ -228,16 +228,16 @@ public static async Task> SendCardsAsync(IMessageC public static Task> SendCardAsync(IMessageChannel channel, BaseKookClient client, ICard card, RequestOptions options, IQuote quote = null, IUser ephemeralUser = null) - => SendCardsAsync(channel, client, new[] {card}, options, quote: quote, ephemeralUser: ephemeralUser); + => SendCardsAsync(channel, client, new[] { card }, options, quote: quote, ephemeralUser: ephemeralUser); public static Task> SendFileAsync(IMessageChannel channel, - BaseKookClient client, string path, string fileName, AttachmentType type, RequestOptions options, + BaseKookClient client, string path, string fileName, AttachmentType type, RequestOptions options, IQuote quote = null, IUser ephemeralUser = null) => SendFileAsync(channel, client, new FileAttachment(path, fileName, type), options, quote: quote, ephemeralUser: ephemeralUser); public static Task> SendFileAsync(IMessageChannel channel, - BaseKookClient client, Stream stream, string fileName, AttachmentType type, RequestOptions options, + BaseKookClient client, Stream stream, string fileName, AttachmentType type, RequestOptions options, IQuote quote = null, IUser ephemeralUser = null) => SendFileAsync(channel, client, new FileAttachment(stream, fileName, type), options, quote: quote, ephemeralUser: ephemeralUser); @@ -251,7 +251,7 @@ public static async Task> SendFileAsync(IMessageCh case CreateAttachmentMode.FilePath: case CreateAttachmentMode.Stream: CreateAssetResponse assetResponse = await client.ApiClient - .CreateAssetAsync(new CreateAssetParams {File = attachment.Stream, FileName = attachment.FileName}, options); + .CreateAssetAsync(new CreateAssetParams { File = attachment.Stream, FileName = attachment.FileName }, options); attachment.Uri = new Uri(assetResponse.Url); break; case CreateAttachmentMode.AssetUri: @@ -281,7 +281,7 @@ public static async Task> SendFileAsync(IMessageCh "Unknown attachment type") }; } - + public static Task DeleteMessageAsync(IMessageChannel channel, Guid messageId, BaseKookClient client, RequestOptions options) => MessageHelper.DeleteAsync(messageId, client, options); @@ -394,7 +394,7 @@ public static async Task> SendDirectMessageAsync(I QuotedMessageId = quote?.QuotedMessageId, }; CreateDirectMessageResponse model = await client.ApiClient.CreateDirectMessageAsync(args, options).ConfigureAwait(false); - return new Cacheable(null, model.MessageId, false, + return new Cacheable(null, model.MessageId, false, async () => await channel.GetMessageAsync(model.MessageId) as IUserMessage); } @@ -406,15 +406,15 @@ public static async Task> SendDirectCardsAsync(IDM } public static Task> SendDirectCardAsync(IDMChannel channel, BaseKookClient client, ICard card, RequestOptions options, IQuote quote = null) - => SendDirectCardsAsync(channel, client, new[] {card}, options, quote: quote); + => SendDirectCardsAsync(channel, client, new[] { card }, options, quote: quote); public static Task> SendDirectFileAsync(IDMChannel channel, - BaseKookClient client, string path, string fileName, AttachmentType type, RequestOptions options, + BaseKookClient client, string path, string fileName, AttachmentType type, RequestOptions options, IQuote quote = null) => SendDirectFileAsync(channel, client, new FileAttachment(path, fileName, type), options, quote: quote); public static Task> SendDirectFileAsync(IDMChannel channel, - BaseKookClient client, Stream stream, string fileName, AttachmentType type, RequestOptions options, + BaseKookClient client, Stream stream, string fileName, AttachmentType type, RequestOptions options, IQuote quote = null) => SendDirectFileAsync(channel, client, new FileAttachment(stream, fileName, type), options, quote: quote); @@ -426,7 +426,7 @@ public static async Task> SendDirectFileAsync(IDMC case CreateAttachmentMode.FilePath: case CreateAttachmentMode.Stream: CreateAssetResponse assetResponse = await client.ApiClient - .CreateAssetAsync(new CreateAssetParams {File = attachment.Stream, FileName = attachment.FileName}, options); + .CreateAssetAsync(new CreateAssetParams { File = attachment.Stream, FileName = attachment.FileName }, options); attachment.Uri = new Uri(assetResponse.Url); break; case CreateAttachmentMode.AssetUri: @@ -456,7 +456,7 @@ public static async Task> SendDirectFileAsync(IDMC "Unknown attachment type") }; } - + public static async Task ModifyDirectMessageAsync(IDMChannel channel, Guid messageId, Action func, BaseKookClient client, RequestOptions options) @@ -507,7 +507,8 @@ public static async Task ModifyPermissionOverwriteAsync IGuildUser user, Func func, RequestOptions options) { var perms = channel.UserPermissionOverwrites.SingleOrDefault(x => x.Target.Id == user.Id)?.Permissions; - if (!perms.HasValue) return null; + if (!perms.HasValue) + return null; perms = func(perms.Value); var args = new ModifyChannelPermissionOverwriteParams(channel.Id, PermissionOverwriteTargetType.User, user.Id, perms.Value.AllowValue, perms.Value.DenyValue); @@ -520,7 +521,8 @@ public static async Task ModifyPermissionOverwriteAsync IRole role, Func func, RequestOptions options) { var perms = channel.RolePermissionOverwrites.SingleOrDefault(x => x.Target == role.Id)?.Permissions; - if (!perms.HasValue) return null; + if (!perms.HasValue) + return null; perms = func(perms.Value); var args = new ModifyChannelPermissionOverwriteParams(channel.Id, PermissionOverwriteTargetType.Role, role.Id, perms.Value.AllowValue, perms.Value.DenyValue); @@ -553,8 +555,8 @@ public static async Task CreateInviteAsync(IGuildChannel channel, Ba { GuildId = channel.GuildId, ChannelId = channel.Id, - MaxAge = (InviteMaxAge) (maxAge ?? 0), - MaxUses = (InviteMaxUses) (maxUses ?? -1), + MaxAge = (InviteMaxAge)(maxAge ?? 0), + MaxUses = (InviteMaxUses)(maxUses ?? -1), }; var model = await client.ApiClient.CreateGuildInviteAsync(args, options).ConfigureAwait(false); var invites = await client.ApiClient.GetGuildInvitesAsync(channel.GuildId, channel.Id, options: options) @@ -565,7 +567,7 @@ public static async Task CreateInviteAsync(IGuildChannel channel, Ba public static Task CreateInviteAsync(IGuildChannel channel, BaseKookClient client, InviteMaxAge maxAge, InviteMaxUses maxUses, RequestOptions options) { - return CreateInviteAsync(channel, client, (int?) maxAge, (int?) maxUses, options); + return CreateInviteAsync(channel, client, (int?)maxAge, (int?)maxUses, options); } #endregion @@ -621,4 +623,4 @@ public static async Task> GetConnectedUsersAs } #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Channels/IRestAudioChannel.cs b/src/Kook.Net.Rest/Entities/Channels/IRestAudioChannel.cs index dd9b0c95..a1b0b421 100644 --- a/src/Kook.Net.Rest/Entities/Channels/IRestAudioChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/IRestAudioChannel.cs @@ -1,5 +1,5 @@ -namespace Kook.Rest; +namespace Kook.Rest; public interface IRestAudioChannel : IAudioChannel { -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Channels/IRestMessageChannel.cs b/src/Kook.Net.Rest/Entities/Channels/IRestMessageChannel.cs index 434107cf..007c9262 100644 --- a/src/Kook.Net.Rest/Entities/Channels/IRestMessageChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/IRestMessageChannel.cs @@ -62,4 +62,4 @@ public interface IRestMessageChannel : IMessageChannel /// Paged collection of messages. /// IAsyncEnumerable> GetMessagesAsync(IMessage referenceMessage, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, RequestOptions options = null); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Channels/IRestPrivateChannel.cs b/src/Kook.Net.Rest/Entities/Channels/IRestPrivateChannel.cs index fbdf9f4b..f5c1048c 100644 --- a/src/Kook.Net.Rest/Entities/Channels/IRestPrivateChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/IRestPrivateChannel.cs @@ -9,4 +9,4 @@ public interface IRestPrivateChannel : IPrivateChannel /// Users that can access this channel. /// new IReadOnlyCollection Recipients { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Channels/RestCategoryChannel.cs b/src/Kook.Net.Rest/Entities/Channels/RestCategoryChannel.cs index df94df8f..27b3c546 100644 --- a/src/Kook.Net.Rest/Entities/Channels/RestCategoryChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/RestCategoryChannel.cs @@ -1,6 +1,5 @@ -using Model = Kook.API.Channel; - using System.Diagnostics; +using Model = Kook.API.Channel; namespace Kook.Rest; @@ -11,7 +10,7 @@ namespace Kook.Rest; public class RestCategoryChannel : RestGuildChannel, ICategoryChannel { #region RestCategoryChannel - + internal RestCategoryChannel(BaseKookClient kook, IGuild guild, ulong id) : base(kook, guild, id, ChannelType.Category) { @@ -22,13 +21,13 @@ internal RestCategoryChannel(BaseKookClient kook, IGuild guild, ulong id) entity.Update(model); return entity; } - + #endregion - + private string DebuggerDisplay => $"{Name} ({Id}, Category)"; - + #region IChannel - + /// /// This method is not supported with category channels. IAsyncEnumerable> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options) @@ -37,6 +36,6 @@ IAsyncEnumerable> IChannel.GetUsersAsync(CacheMode mo /// This method is not supported with category channels. Task IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => throw new NotSupportedException(); - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Channels/RestChannel.cs b/src/Kook.Net.Rest/Entities/Channels/RestChannel.cs index a948d403..189a7a96 100644 --- a/src/Kook.Net.Rest/Entities/Channels/RestChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/RestChannel.cs @@ -8,7 +8,7 @@ namespace Kook.Rest; public class RestChannel : RestEntity, IChannel, IUpdateable { #region RestChannel - + internal RestChannel(BaseKookClient kook, ulong id) : base(kook, id) { @@ -34,7 +34,7 @@ ChannelType.Text or ChannelType.Voice }; } internal virtual void Update(Model model) { } - + /// public virtual Task UpdateAsync(RequestOptions options = null) => Task.Delay(0); @@ -51,6 +51,6 @@ Task IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions optio /// IAsyncEnumerable> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options) => AsyncEnumerable.Empty>(); //Overridden - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Channels/RestDMChannel.cs b/src/Kook.Net.Rest/Entities/Channels/RestDMChannel.cs index 703595cf..29543135 100644 --- a/src/Kook.Net.Rest/Entities/Channels/RestDMChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/RestDMChannel.cs @@ -1,7 +1,7 @@ -using System.Collections.Immutable; -using System.Diagnostics; using Kook.API.Rest; using Kook.Utils; +using System.Collections.Immutable; +using System.Diagnostics; using Model = Kook.API.UserChat; namespace Kook.Rest; @@ -32,17 +32,17 @@ public class RestDMChannel : RestChannel, IDMChannel, IRestPrivateChannel, IRest /// Gets the current logged-in user. /// public RestUser CurrentUser { get; } - + /// /// Gets the recipient of the channel. /// public RestUser Recipient { get; } - + /// /// Gets a collection that is the current logged-in user and the recipient. /// public IReadOnlyCollection Users => ImmutableArray.Create(CurrentUser, Recipient); - + internal RestDMChannel(BaseKookClient kook, Guid chatCode, ulong recipientId) : base(kook, default) { @@ -67,7 +67,7 @@ public override async Task UpdateAsync(RequestOptions options = null) var model = await Kook.ApiClient.GetUserChatAsync(Id, options).ConfigureAwait(false); Update(model); } - + /// public Task CloseAsync(RequestOptions options = null) => ChannelHelper.DeleteDMChannelAsync(this, Kook, options); @@ -100,7 +100,7 @@ public RestUser GetUser(ulong id) /// public Task> SendTextAsync(string text, IQuote quote = null, RequestOptions options = null) => ChannelHelper.SendDirectMessageAsync(this, Kook, MessageType.KMarkdown, text, options, quote: quote); - + /// /// Sends a file to this message channel. /// @@ -116,7 +116,7 @@ public Task> SendTextAsync(string text, IQuote quo /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the identifier and timestamp of the sent message. /// - public Task> SendFileAsync(string path, string fileName = null, + public Task> SendFileAsync(string path, string fileName = null, AttachmentType type = AttachmentType.File, IQuote quote = null, RequestOptions options = null) => ChannelHelper.SendDirectFileAsync(this, Kook, path, fileName, type, options, quote: quote); /// @@ -134,7 +134,7 @@ public Task> SendFileAsync(string path, string fil /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the identifier and timestamp of the sent message. /// - public Task> SendFileAsync(Stream stream, string fileName = null, + public Task> SendFileAsync(Stream stream, string fileName = null, AttachmentType type = AttachmentType.File, IQuote quote = null, RequestOptions options = null) => ChannelHelper.SendDirectFileAsync(this, Kook, stream, fileName, type, options, quote: quote); /// @@ -150,7 +150,7 @@ public Task> SendFileAsync(Stream stream, string f /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the identifier and timestamp of the sent message. /// - public Task> SendFileAsync(FileAttachment attachment, + public Task> SendFileAsync(FileAttachment attachment, IQuote quote = null, RequestOptions options = null) => ChannelHelper.SendDirectFileAsync(this, Kook, attachment, options, quote: quote); @@ -177,7 +177,7 @@ public Task> SendCardsAsync(IEnumerable car /// A task that represents an asynchronous send operation for delivering the message. The task result /// contains the identifier and timestamp of the sent message. /// - public Task> SendCardAsync(ICard card, IQuote quote = null, RequestOptions options = null) + public Task> SendCardAsync(ICard card, IQuote quote = null, RequestOptions options = null) => ChannelHelper.SendDirectCardAsync(this, Kook, card, options, quote: quote); /// @@ -192,7 +192,7 @@ public IAsyncEnumerable> GetMessagesAsync(Guid /// public IAsyncEnumerable> GetMessagesAsync(IMessage referenceMessage, Direction dir, int limit = KookConfig.MaxMessagesPerBatch, RequestOptions options = null) => ChannelHelper.GetDirectMessagesAsync(this, Kook, referenceMessage.Id, dir, limit, true, options); - + #endregion #region Messages @@ -213,7 +213,7 @@ public Task ModifyMessageAsync(Guid messageId, Action func, R /// IUser IDMChannel.Recipient => Recipient; #endregion - + #region IRestPrivateChannel /// IReadOnlyCollection IRestPrivateChannel.Recipients => ImmutableArray.Create(Recipient); @@ -259,7 +259,7 @@ IAsyncEnumerable> IMessageChannel.GetMessagesAsync return AsyncEnumerable.Empty>(); } /// - Task> IMessageChannel.SendFileAsync(string path, string fileName, + Task> IMessageChannel.SendFileAsync(string path, string fileName, AttachmentType type, IQuote quote, IUser ephemeralUser, RequestOptions options) => SendFileAsync(path, fileName, type, quote, options); /// @@ -267,7 +267,7 @@ Task> IMessageChannel.SendFileAsync(Stream stream, AttachmentType type, IQuote quote, IUser ephemeralUser, RequestOptions options) => SendFileAsync(stream, fileName, type, quote, options); /// - Task> IMessageChannel.SendFileAsync(FileAttachment attachment, + Task> IMessageChannel.SendFileAsync(FileAttachment attachment, IQuote quote, IUser ephemeralUser, RequestOptions options) => SendFileAsync(attachment, quote, options); /// @@ -282,9 +282,9 @@ Task> IMessageChannel.SendCardsAsync(IEnumerable> IMessageChannel.SendCardAsync(ICard card, IQuote quote, IUser ephemeralUser, RequestOptions options) => SendCardAsync(card, quote, options); - + #endregion - + /// /// Gets a string that represents the Username#IdentifyNumber of the recipient. /// @@ -295,14 +295,14 @@ Task> IMessageChannel.SendCardAsync(ICard card, private string DebuggerDisplay => $"@{Recipient} ({Id}, DM)"; #region IChannel - + /// Task IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult(GetUser(id)); - + /// IAsyncEnumerable> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options) => ImmutableArray.Create>(Users).ToAsyncEnumerable(); #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Channels/RestGuildChannel.cs b/src/Kook.Net.Rest/Entities/Channels/RestGuildChannel.cs index da88df3e..3b73d955 100644 --- a/src/Kook.Net.Rest/Entities/Channels/RestGuildChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/RestGuildChannel.cs @@ -1,7 +1,6 @@ -using Model = Kook.API.Channel; - -using System.Collections.Immutable; using Kook.API; +using System.Collections.Immutable; +using Model = Kook.API.Channel; namespace Kook.Rest; @@ -11,7 +10,7 @@ public class RestGuildChannel : RestChannel, IGuildChannel private ImmutableArray _rolePermissionOverwrites; private ImmutableArray _userPermissionOverwrites; - + /// public virtual IReadOnlyCollection RolePermissionOverwrites => _rolePermissionOverwrites; /// @@ -34,7 +33,7 @@ public class RestGuildChannel : RestChannel, IGuildChannel public ulong GuildId => Guild.Id; /// public ulong CreatorId { get; private set; } - + internal RestGuildChannel(BaseKookClient kook, IGuild guild, ulong id, ChannelType type) : base(kook, id) { @@ -63,7 +62,7 @@ internal override void Update(Model model) Name = model.Name; Position = model.Position; CreatorId = model.CreatorId; - + if (model.UserPermissionOverwrites is not null) { var overwrites = model.UserPermissionOverwrites; @@ -106,11 +105,11 @@ public async Task ModifyAsync(Action func, Request /// public Task GetCreatorAsync(RequestOptions options = null) => ClientHelper.GetUserAsync(Kook, CreatorId, options); - + /// public Task DeleteAsync(RequestOptions options = null) => ChannelHelper.DeleteGuildChannelAsync(this, Kook, options); - + /// public override async Task UpdateAsync(RequestOptions options = null) { @@ -150,7 +149,7 @@ public override async Task UpdateAsync(RequestOptions options = null) } return null; } - + /// /// Adds the permission overwrite for the given user. /// @@ -161,7 +160,7 @@ public override async Task UpdateAsync(RequestOptions options = null) /// public async Task AddPermissionOverwriteAsync(IGuildUser user, RequestOptions options = null) { - var perms = await ChannelHelper.AddPermissionOverwriteAsync(this, Kook, user, options).ConfigureAwait(false); + var perms = await ChannelHelper.AddPermissionOverwriteAsync(this, Kook, user, options).ConfigureAwait(false); _userPermissionOverwrites = _userPermissionOverwrites.Add(perms); } /// @@ -233,7 +232,7 @@ public async Task RemovePermissionOverwriteAsync(IRole role, RequestOptions opti public async Task ModifyPermissionOverwriteAsync(IGuildUser user, Func func, RequestOptions options = null) { var perms = await ChannelHelper.ModifyPermissionOverwriteAsync(this, Kook, user, func, options).ConfigureAwait(false); - + for (int i = 0; i < _userPermissionOverwrites.Length; i++) { if (_userPermissionOverwrites[i].Target.Id == user.Id) @@ -257,7 +256,7 @@ public async Task ModifyPermissionOverwriteAsync(IGuildUser user, Func func, RequestOptions options = null) { var perms = await ChannelHelper.ModifyPermissionOverwriteAsync(this, Kook, role, func, options).ConfigureAwait(false); - + for (int i = 0; i < _rolePermissionOverwrites.Length; i++) { if (_rolePermissionOverwrites[i].Target == role.Id) @@ -268,7 +267,7 @@ public async Task ModifyPermissionOverwriteAsync(IRole role, Func /// Gets the name of this channel. /// @@ -276,11 +275,11 @@ public async Task ModifyPermissionOverwriteAsync(IRole role, Func public override string ToString() => Name; - + #endregion #region IGuildChannel - + /// IGuild IGuildChannel.Guild { @@ -291,14 +290,14 @@ IGuild IGuildChannel.Guild throw new InvalidOperationException("Unable to return this entity's parent unless it was fetched through that object."); } } - + /// OverwritePermissions? IGuildChannel.GetPermissionOverwrite(IRole role) => GetPermissionOverwrite(role); /// OverwritePermissions? IGuildChannel.GetPermissionOverwrite(IUser user) => GetPermissionOverwrite(user); - + /// async Task IGuildChannel.AddPermissionOverwriteAsync(IRole role, RequestOptions options) => await AddPermissionOverwriteAsync(role, options).ConfigureAwait(false); @@ -332,9 +331,9 @@ async Task IGuildChannel.GetCreatorAsync(CacheMode mode, RequestOptions o else return null; } - + #endregion - + #region IChannel /// IAsyncEnumerable> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options) @@ -343,4 +342,4 @@ IAsyncEnumerable> IChannel.GetUsersAsync(CacheMode mo Task IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult(null); //Overridden in Text/Voice #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Channels/RestTextChannel.cs b/src/Kook.Net.Rest/Entities/Channels/RestTextChannel.cs index 46772ab9..c2124ed1 100644 --- a/src/Kook.Net.Rest/Entities/Channels/RestTextChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/RestTextChannel.cs @@ -1,13 +1,12 @@ -using Model = Kook.API.Channel; - -using System.Diagnostics; -using System.Text.Encodings.Web; -using System.Text.Json; -using System.Text.Json.Serialization; using Kook.API; using Kook.API.Rest; using Kook.Net.Converters; using Kook.Utils; +using System.Diagnostics; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using Model = Kook.API.Channel; namespace Kook.Rest; @@ -18,7 +17,7 @@ namespace Kook.Rest; public class RestTextChannel : RestGuildChannel, IRestMessageChannel, ITextChannel { #region RestTextChannel - + /// public string Topic { get; private set; } /// @@ -31,12 +30,12 @@ public class RestTextChannel : RestGuildChannel, IRestMessageChannel, ITextChann public string KMarkdownMention => MentionUtils.KMarkdownMentionChannel(Id); /// public string PlainTextMention => MentionUtils.PlainTextMentionChannel(Id); - + internal RestTextChannel(BaseKookClient kook, IGuild guild, ulong id) : base(kook, guild, id, ChannelType.Text) { } - + internal new static RestTextChannel Create(BaseKookClient kook, IGuild guild, Model model) { var entity = new RestTextChannel(kook, guild, model.Id); @@ -52,14 +51,14 @@ internal override void Update(Model model) SlowModeInterval = model.SlowMode / 1000; IsPermissionSynced = model.PermissionSync; } - + /// public virtual async Task ModifyAsync(Action func, RequestOptions options = null) { var model = await ChannelHelper.ModifyAsync(this, Kook, func, options).ConfigureAwait(false); Update(model); } - + /// /// Gets a user in this channel. /// @@ -150,11 +149,11 @@ public async Task CreateInviteAsync(InviteMaxAge maxAge = InviteMaxAge. => await ChannelHelper.CreateInviteAsync(this, Kook, maxAge, maxUses, options).ConfigureAwait(false); #endregion - + private string DebuggerDisplay => $"{Name} ({Id}, Text)"; #region IChannel - + /// async Task IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) { @@ -163,7 +162,7 @@ async Task IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions else return null; } - + /// IAsyncEnumerable> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options) { @@ -174,9 +173,9 @@ IAsyncEnumerable> IChannel.GetUsersAsync(CacheMode mo } #endregion - + #region IGuildChannel - + /// async Task IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) { @@ -192,35 +191,35 @@ IAsyncEnumerable> IGuildChannel.GetUsersAsync(Ca ? GetUsersAsync(options) : AsyncEnumerable.Empty>(); } - + #endregion - + #region IMessageChannel /// Task> IMessageChannel.SendFileAsync(string path, string fileName, AttachmentType type, IQuote quote, IUser ephemeralUser, RequestOptions options) - => SendFileAsync(path, fileName, type, (Quote) quote, ephemeralUser, options); + => SendFileAsync(path, fileName, type, (Quote)quote, ephemeralUser, options); /// Task> IMessageChannel.SendFileAsync(Stream stream, string fileName, AttachmentType type, IQuote quote, IUser ephemeralUser, RequestOptions options) - => SendFileAsync(stream, fileName, type, (Quote) quote, ephemeralUser, options); + => SendFileAsync(stream, fileName, type, (Quote)quote, ephemeralUser, options); /// Task> IMessageChannel.SendFileAsync(FileAttachment attachment, IQuote quote, IUser ephemeralUser, RequestOptions options) - => SendFileAsync(attachment, (Quote) quote, ephemeralUser, options); + => SendFileAsync(attachment, (Quote)quote, ephemeralUser, options); /// Task> IMessageChannel.SendTextAsync(string text, IQuote quote, IUser ephemeralUser, RequestOptions options) - => SendTextAsync(text, (Quote) quote, ephemeralUser, options); + => SendTextAsync(text, (Quote)quote, ephemeralUser, options); /// Task> IMessageChannel.SendCardAsync(ICard card, IQuote quote, IUser ephemeralUser, RequestOptions options) - => SendCardAsync(card, (Quote) quote, ephemeralUser, options); + => SendCardAsync(card, (Quote)quote, ephemeralUser, options); /// Task> IMessageChannel.SendCardsAsync(IEnumerable cards, IQuote quote, IUser ephemeralUser, RequestOptions options) - => SendCardsAsync(cards, (Quote) quote, ephemeralUser, options); + => SendCardsAsync(cards, (Quote)quote, ephemeralUser, options); /// async Task IMessageChannel.GetMessageAsync(Guid id, CacheMode mode, RequestOptions options) @@ -258,22 +257,22 @@ IAsyncEnumerable> IMessageChannel.GetMessagesAsync /// async Task> ITextChannel.GetPinnedMessagesAsync(RequestOptions options) => await GetPinnedMessagesAsync(options).ConfigureAwait(false); - + /// public Task DeleteMessageAsync(Guid messageId, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, messageId, Kook, options); /// public Task DeleteMessageAsync(IMessage message, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, message.Id, Kook, options); - + /// public async Task ModifyMessageAsync(Guid messageId, Action func, RequestOptions options = null) => await ChannelHelper.ModifyMessageAsync(this, messageId, func, Kook, options).ConfigureAwait(false); #endregion - + #region INestedChannel - + /// async Task INestedChannel.GetCategoryAsync(CacheMode mode, RequestOptions options) { @@ -281,6 +280,6 @@ async Task INestedChannel.GetCategoryAsync(CacheMode mode, Req return (await Guild.GetChannelAsync(CategoryId.Value, mode, options).ConfigureAwait(false)) as ICategoryChannel; return null; } - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Channels/RestVoiceChannel.cs b/src/Kook.Net.Rest/Entities/Channels/RestVoiceChannel.cs index 389159fd..3de083b4 100644 --- a/src/Kook.Net.Rest/Entities/Channels/RestVoiceChannel.cs +++ b/src/Kook.Net.Rest/Entities/Channels/RestVoiceChannel.cs @@ -1,7 +1,6 @@ using System.Collections.Immutable; -using Model = Kook.API.Channel; - using System.Diagnostics; +using Model = Kook.API.Channel; namespace Kook.Rest; @@ -34,7 +33,7 @@ internal RestVoiceChannel(BaseKookClient kook, IGuild guild, ulong id) : base(kook, guild, id, ChannelType.Voice) { } - + internal new static RestVoiceChannel Create(BaseKookClient kook, IGuild guild, Model model) { var entity = new RestVoiceChannel(kook, guild, model.Id); @@ -52,7 +51,7 @@ internal override void Update(Model model) IsPermissionSynced = model.PermissionSync; HasPassword = model.HasPassword; } - + /// public async Task ModifyAsync(Action func, RequestOptions options = null) { @@ -62,7 +61,7 @@ public async Task ModifyAsync(Action func, Request public async Task> GetConnectedUsersAsync(RequestOptions options) => await ChannelHelper.GetConnectedUsersAsync(this, Guild, Kook, options).ConfigureAwait(false); - + /// /// Gets the parent (category) channel of this channel. /// @@ -77,7 +76,7 @@ public Task GetCategoryAsync(RequestOptions options = null) #endregion #region Invites - + /// public async Task> GetInvitesAsync(RequestOptions options = null) => await ChannelHelper.GetInvitesAsync(this, Kook, options).ConfigureAwait(false); @@ -89,12 +88,12 @@ public async Task CreateInviteAsync(InviteMaxAge maxAge = InviteMaxAge. => await ChannelHelper.CreateInviteAsync(this, Kook, maxAge, maxUses, options).ConfigureAwait(false); #endregion - + private string DebuggerDisplay => $"{Name} ({Id}, Voice)"; - - + + #region IGuildChannel - + /// Task IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult(null); @@ -103,11 +102,11 @@ IAsyncEnumerable> IGuildChannel.GetUsersAsync(Ca { return AsyncEnumerable.Empty>(); } - + #endregion - + #region INestedChannel - + /// async Task INestedChannel.GetCategoryAsync(CacheMode mode, RequestOptions options) { @@ -115,9 +114,9 @@ async Task INestedChannel.GetCategoryAsync(CacheMode mode, Req return (await Guild.GetChannelAsync(CategoryId.Value, mode, options).ConfigureAwait(false)) as ICategoryChannel; return null; } - + #endregion - + #region IVoiceChannel async Task> IVoiceChannel.GetConnectedUsersAsync(CacheMode mode, RequestOptions options) @@ -129,4 +128,4 @@ async Task> IVoiceChannel.GetConnectedUsersAsync(Cach } #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Games/GameHelper.cs b/src/Kook.Net.Rest/Entities/Games/GameHelper.cs index 9f3dd3da..597972dd 100644 --- a/src/Kook.Net.Rest/Entities/Games/GameHelper.cs +++ b/src/Kook.Net.Rest/Entities/Games/GameHelper.cs @@ -4,7 +4,7 @@ namespace Kook.Rest; internal static class GameHelper { - public static async Task DeleteAsync(IGame game, BaseKookClient client, + public static async Task DeleteAsync(IGame game, BaseKookClient client, RequestOptions options) { await client.ApiClient.DeleteGameAsync(game.Id, options).ConfigureAwait(false); @@ -28,4 +28,4 @@ public static async Task ModifyAsync(IGame game, BaseKookClient client var model = await client.ApiClient.ModifyGameAsync(args, options).ConfigureAwait(false); return RestGame.Create(client, model); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Games/RestGame.cs b/src/Kook.Net.Rest/Entities/Games/RestGame.cs index da9f25ae..583c4af8 100644 --- a/src/Kook.Net.Rest/Entities/Games/RestGame.cs +++ b/src/Kook.Net.Rest/Entities/Games/RestGame.cs @@ -10,7 +10,7 @@ public class RestGame : RestEntity, IGame { private ImmutableArray _productNames; private ImmutableArray _processNames; - + /// public string Name { get; private set; } /// @@ -25,12 +25,12 @@ public class RestGame : RestEntity, IGame public IReadOnlyCollection ProductNames => _productNames.ToReadOnlyCollection(); /// public IReadOnlyCollection ProcessNames => _processNames.ToReadOnlyCollection(); - + internal RestGame(BaseKookClient kook, int id) : base(kook, id) { } - + internal static RestGame Create(BaseKookClient kook, Model model) { var entity = new RestGame(kook, model.Id); @@ -59,8 +59,8 @@ public async Task DeleteAsync(RequestOptions options = null) { await GameHelper.DeleteAsync(this, Kook, options).ConfigureAwait(false); } - + /// - async Task IGame.ModifyAsync(Action func, RequestOptions options) + async Task IGame.ModifyAsync(Action func, RequestOptions options) => await ModifyAsync(func, options); -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Guilds/GuildHelper.cs b/src/Kook.Net.Rest/Entities/Guilds/GuildHelper.cs index 27772184..ac9d3266 100644 --- a/src/Kook.Net.Rest/Entities/Guilds/GuildHelper.cs +++ b/src/Kook.Net.Rest/Entities/Guilds/GuildHelper.cs @@ -1,7 +1,7 @@ -using System.Collections.Immutable; -using System.Runtime.CompilerServices; using Kook.API; using Kook.API.Rest; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; namespace Kook.Rest; @@ -49,7 +49,7 @@ public static int GetMaxBitrate(IGuild guild) BoostLevel.Level5 or BoostLevel.Level6 => 320, _ => 96 }; - + return tierFactor * 1000; } public static ulong GetUploadLimit(IGuild guild) @@ -66,9 +66,9 @@ public static ulong GetUploadLimit(IGuild guild) }; var mebibyte = Math.Pow(2, 20); - return (ulong) (tierFactor * mebibyte); + return (ulong)(tierFactor * mebibyte); } - + #endregion #region Invites @@ -81,7 +81,7 @@ public static async Task> GetInvitesAsync(IGuild ? guild.GetChannelAsync(x.ChannelId.Value, CacheMode.CacheOnly).GetAwaiter().GetResult() : null, x)).ToImmutableArray(); } - + /// /// may not be equal to zero. /// and must be greater than zero. @@ -93,8 +93,8 @@ public static async Task CreateInviteAsync(IGuild guild, BaseKookCli var args = new CreateGuildInviteParams() { GuildId = guild.Id, - MaxAge = (InviteMaxAge) (maxAge ?? 0), - MaxUses = (InviteMaxUses) (maxUses ?? -1), + MaxAge = (InviteMaxAge)(maxAge ?? 0), + MaxUses = (InviteMaxUses)(maxUses ?? -1), }; var model = await client.ApiClient.CreateGuildInviteAsync(args, options).ConfigureAwait(false); var invites = await client.ApiClient.GetGuildInvitesAsync(guild.Id, options: options).FlattenAsync().ConfigureAwait(false); @@ -103,22 +103,23 @@ public static async Task CreateInviteAsync(IGuild guild, BaseKookCli ? guild.GetChannelAsync(invite.ChannelId.Value, CacheMode.CacheOnly).GetAwaiter().GetResult() : null, invite); } - + public static Task CreateInviteAsync(IGuild channel, BaseKookClient client, InviteMaxAge maxAge, InviteMaxUses maxUses, RequestOptions options) { - return CreateInviteAsync(channel, client, (int?) maxAge, (int?) maxUses, options); + return CreateInviteAsync(channel, client, (int?)maxAge, (int?)maxUses, options); } #endregion - + #region Roles - + /// is null. public static async Task CreateRoleAsync(IGuild guild, BaseKookClient client, string name, RequestOptions options) { - if (name == null) throw new ArgumentNullException(paramName: nameof(name)); + if (name == null) + throw new ArgumentNullException(paramName: nameof(name)); var createGuildRoleParams = new CreateGuildRoleParams { @@ -130,9 +131,9 @@ public static async Task CreateRoleAsync(IGuild guild, BaseKookClient return RestRole.Create(client, guild, model); } - + #endregion - + #region Users public static IAsyncEnumerable> GetUsersAsync(IGuild guild, BaseKookClient client, int limit, int fromPage, RequestOptions options) @@ -141,7 +142,7 @@ public static IAsyncEnumerable> GetUsersAsync .Select(x => x .Select(y => RestGuildUser.Create(client, guild, y)).ToImmutableArray() as IReadOnlyCollection); } - + public static async Task GetUserAsync(IGuild guild, BaseKookClient client, ulong id, RequestOptions options) { @@ -150,14 +151,14 @@ public static async Task GetUserAsync(IGuild guild, BaseKookClien return RestGuildUser.Create(client, guild, model); return null; } - - public static async Task<(IReadOnlyCollection Muted, IReadOnlyCollection Deafened)> GetGuildMutedDeafenedUsersAsync(IGuild guild, BaseKookClient client, + + public static async Task<(IReadOnlyCollection Muted, IReadOnlyCollection Deafened)> GetGuildMutedDeafenedUsersAsync(IGuild guild, BaseKookClient client, RequestOptions options) { var models = await client.ApiClient.GetGuildMutedDeafenedUsersAsync(guild.Id, options).ConfigureAwait(false); return (models.Muted.UserIds, models.Deafened.UserIds); } - + public static async Task MuteUserAsync(IGuildUser user, BaseKookClient client, RequestOptions options) { CreateOrRemoveGuildMuteDeafParams args = new() @@ -168,7 +169,7 @@ public static async Task MuteUserAsync(IGuildUser user, BaseKookClient client, R }; await client.ApiClient.CreateGuildMuteDeafAsync(args, options).ConfigureAwait(false); } - + public static async Task DeafenUserAsync(IGuildUser user, BaseKookClient client, RequestOptions options) { CreateOrRemoveGuildMuteDeafParams args = new() @@ -179,7 +180,7 @@ public static async Task DeafenUserAsync(IGuildUser user, BaseKookClient client, }; await client.ApiClient.CreateGuildMuteDeafAsync(args, options).ConfigureAwait(false); } - + public static async Task UnmuteUserAsync(IGuildUser user, BaseKookClient client, RequestOptions options) { CreateOrRemoveGuildMuteDeafParams args = new() @@ -190,7 +191,7 @@ public static async Task UnmuteUserAsync(IGuildUser user, BaseKookClient client, }; await client.ApiClient.RemoveGuildMuteDeafAsync(args, options).ConfigureAwait(false); } - + public static async Task UndeafenUserAsync(IGuildUser user, BaseKookClient client, RequestOptions options) { CreateOrRemoveGuildMuteDeafParams args = new() @@ -201,13 +202,13 @@ public static async Task UndeafenUserAsync(IGuildUser user, BaseKookClient clien }; await client.ApiClient.RemoveGuildMuteDeafAsync(args, options).ConfigureAwait(false); } - + public static IAsyncEnumerable> SearchUsersAsync(IGuild guild, BaseKookClient client, Action func, int limit, RequestOptions options) { var models = client.ApiClient.GetGuildMembersAsync(guild.Id, func, limit, 1, options); return models.Select(x => x.Select(y => RestGuildUser.Create(client, guild, y)).ToImmutableArray() as IReadOnlyCollection); } - + #endregion #region Channels @@ -227,14 +228,15 @@ public static async Task> GetChannelsAsync return models.Select(x => RestGuildChannel.Create(client, guild, x)).ToImmutableArray(); } /// is null. - public static async Task CreateTextChannelAsync(IGuild guild, BaseKookClient client, + public static async Task CreateTextChannelAsync(IGuild guild, BaseKookClient client, string name, RequestOptions options, Action func) { - if (name == null) throw new ArgumentNullException(paramName: nameof(name)); + if (name == null) + throw new ArgumentNullException(paramName: nameof(name)); var props = new CreateTextChannelProperties(); func?.Invoke(props); - + var args = new CreateGuildChannelParams { Name = name, @@ -246,14 +248,15 @@ public static async Task CreateTextChannelAsync(IGuild guild, B return RestTextChannel.Create(client, guild, model); } /// is null. - public static async Task CreateVoiceChannelAsync(IGuild guild, BaseKookClient client, + public static async Task CreateVoiceChannelAsync(IGuild guild, BaseKookClient client, string name, RequestOptions options, Action func) { - if (name == null) throw new ArgumentNullException(paramName: nameof(name)); + if (name == null) + throw new ArgumentNullException(paramName: nameof(name)); var props = new CreateVoiceChannelProperties(); func?.Invoke(props); - + var args = new CreateGuildChannelParams { Name = name, @@ -270,7 +273,8 @@ public static async Task CreateVoiceChannelAsync(IGuild guild, public static async Task CreateCategoryChannelAsync(IGuild guild, BaseKookClient client, string name, RequestOptions options, Action func = null) { - if (name == null) throw new ArgumentNullException(paramName: nameof(name)); + if (name == null) + throw new ArgumentNullException(paramName: nameof(name)); var props = new CreateCategoryChannelProperties(); func?.Invoke(props); @@ -319,7 +323,7 @@ public static async Task RemoveBanAsync(IGuild guild, BaseKookClient client, #endregion #region Emotes - + public static async Task> GetEmotesAsync(IGuild guild, BaseKookClient client, RequestOptions options) { var models = await client.ApiClient.GetGuildEmotesAsync(guild.Id, options: options).FlattenAsync().ConfigureAwait(false); @@ -346,7 +350,8 @@ public static async Task CreateEmoteAsync(IGuild guild, BaseKookClie public static async Task ModifyEmoteNameAsync(IGuild guild, BaseKookClient client, IEmote emote, Action func, RequestOptions options) { - if (func == null) throw new ArgumentNullException(paramName: nameof(func)); + if (func == null) + throw new ArgumentNullException(paramName: nameof(func)); string name = emote.Name; func(name); @@ -354,17 +359,17 @@ public static async Task ModifyEmoteNameAsync(IGuild guild, BaseKookClient clien var args = new ModifyGuildEmoteParams { Name = name, Id = emote.Id }; await client.ApiClient.ModifyGuildEmoteAsync(args, options).ConfigureAwait(false); } - public static async Task DeleteEmoteAsync(IGuild guild, BaseKookClient client, string id, RequestOptions options) + public static async Task DeleteEmoteAsync(IGuild guild, BaseKookClient client, string id, RequestOptions options) => await client.ApiClient.DeleteGuildEmoteAsync(id, options).ConfigureAwait(false); #endregion #region Badges - + public static async Task GetBadgeAsync(IGuild guild, BaseKookClient client, BadgeStyle style, RequestOptions options) { return await client.ApiClient.GetGuildBadgeAsync(guild.Id, style, options).ConfigureAwait(false); } #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Guilds/RecommendInfo.cs b/src/Kook.Net.Rest/Entities/Guilds/RecommendInfo.cs index 9e9c1e3c..f8052d7a 100644 --- a/src/Kook.Net.Rest/Entities/Guilds/RecommendInfo.cs +++ b/src/Kook.Net.Rest/Entities/Guilds/RecommendInfo.cs @@ -43,7 +43,7 @@ public class RecommendInfo : IRecommendInfo internal RecommendInfo() { } - + internal static RecommendInfo Create(Model model) { var entity = new RecommendInfo(); @@ -71,4 +71,4 @@ internal void Update(Model model) AuditStatus = model.AuditStatus; DaysBeforeModify = model.UpdateDayInterval; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Guilds/RestBan.cs b/src/Kook.Net.Rest/Entities/Guilds/RestBan.cs index 3563381e..f9e0bbcc 100644 --- a/src/Kook.Net.Rest/Entities/Guilds/RestBan.cs +++ b/src/Kook.Net.Rest/Entities/Guilds/RestBan.cs @@ -10,7 +10,7 @@ namespace Kook.Rest; public class RestBan : IBan { #region RestBan - + /// /// Gets the banned user. /// @@ -24,7 +24,7 @@ public class RestBan : IBan /// public string Reason { get; } - + internal RestBan(RestUser user, string reason, DateTimeOffset createdAt) { User = user; @@ -35,7 +35,7 @@ internal static RestBan Create(BaseKookClient client, Model model) { return new RestBan(RestUser.Create(client, model.User), model.Reason, model.CreatedAt); } - + /// /// Gets the name of the banned user. /// @@ -44,11 +44,11 @@ internal static RestBan Create(BaseKookClient client, Model model) /// public override string ToString() => User.ToString(); private string DebuggerDisplay => $"{User}: {Reason}"; - + #endregion - + #region IBan /// IUser IBan.User => User; #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Guilds/RestGuild.cs b/src/Kook.Net.Rest/Entities/Guilds/RestGuild.cs index 6242e3f7..8f616083 100644 --- a/src/Kook.Net.Rest/Entities/Guilds/RestGuild.cs +++ b/src/Kook.Net.Rest/Entities/Guilds/RestGuild.cs @@ -1,9 +1,9 @@ +using Kook.API; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics; -using Kook.API; -using Model = Kook.API.Guild; using ExtendedModel = Kook.API.Rest.ExtendedGuild; +using Model = Kook.API.Guild; namespace Kook.Rest; @@ -18,7 +18,7 @@ public class RestGuild : RestEntity, IGuild, IUpdateable private ImmutableDictionary _roles; private ImmutableDictionary _channels; // private ImmutableArray _emotes; - + /// public string Name { get; private set; } /// @@ -57,12 +57,12 @@ public class RestGuild : RestEntity, IGuild, IUpdateable /// Gets a collection of all roles in this guild. /// public IReadOnlyCollection Roles => _roles.ToReadOnlyCollection(); - + /// /// Gets a collection of all channels in this guild. /// public IReadOnlyCollection Channels => _channels.ToReadOnlyCollection(); - + /// /// Gets the features of this guild. /// @@ -91,7 +91,7 @@ public class RestGuild : RestEntity, IGuild, IUpdateable public string AutoDeleteTime { get; private set; } /// public RecommendInfo RecommendInfo { get; private set; } - + internal RestGuild(BaseKookClient client, ulong id) : base(client, id) { @@ -137,7 +137,7 @@ internal void Update(Model model) roles[model.Roles[i].Id] = RestRole.Create(Kook, this, model.Roles[i]); } _roles = roles.ToImmutable(); - + var channels = ImmutableDictionary.CreateBuilder(); if (model.Channels != null) { @@ -146,7 +146,7 @@ internal void Update(Model model) } _channels = channels.ToImmutable(); } - + #endregion #region Generals @@ -166,11 +166,11 @@ public Task public Task>> GetActiveBoostSubscriptionsAsync(RequestOptions options = null) => GuildHelper.GetActiveBoostSubscriptionsAsync(this, Kook, options); - + #endregion - + #region Bans - + /// /// Gets a collection of all users banned in this guild. /// @@ -218,7 +218,7 @@ public Task RemoveBanAsync(IUser user, RequestOptions options = null) /// public Task RemoveBanAsync(ulong userId, RequestOptions options = null) => GuildHelper.RemoveBanAsync(this, Kook, userId, options); - + #endregion // #region Invites @@ -235,7 +235,7 @@ public Task RemoveBanAsync(ulong userId, RequestOptions options = null) // => GuildHelper.GetInvitesAsync(this, Kook, options); // // #endregion - + #region Roles /// @@ -251,7 +251,7 @@ public RestRole GetRole(uint id) return value; return null; } - + /// /// Creates a new role with the provided name. /// @@ -271,7 +271,7 @@ public async Task CreateRoleAsync(string name, RequestOptions options #endregion #region Users - + /// /// Gets a collection of all users in this guild. /// @@ -338,11 +338,11 @@ public Task GetOwnerAsync(RequestOptions options = null) /// public IAsyncEnumerable> SearchUsersAsync(Action func, int limit = KookConfig.MaxUsersPerBatch, RequestOptions options = null) => GuildHelper.SearchUsersAsync(this, Kook, func, limit, options); - + #endregion - + #region Channels - + /// /// Gets a collection of all channels in this guild. /// @@ -431,7 +431,7 @@ public async Task> GetCategoryChannelsA var channels = await GuildHelper.GetChannelsAsync(this, Kook, options).ConfigureAwait(false); return channels.OfType().ToImmutableArray(); } - + /// /// Gets the default text channel in this guild. /// @@ -477,7 +477,7 @@ public async Task GetWelcomeChannelAsync(RequestOptions options } return null; } - + /// /// Creates a new text channel in this guild. /// @@ -514,19 +514,19 @@ public Task CreateVoiceChannelAsync(string name, Action public Task CreateCategoryChannelAsync(string name, Action func = null, RequestOptions options = null) => GuildHelper.CreateCategoryChannelAsync(this, Kook, name, options, func); - + #endregion #region Voices - + /// public async Task MoveUsersAsync(IEnumerable users, IVoiceChannel targetChannel, RequestOptions options) => await ClientHelper.MoveUsersAsync(Kook, users, targetChannel, options).ConfigureAwait(false); #endregion - + #region Emotes - + /// public Task> GetEmotesAsync(RequestOptions options = null) => GuildHelper.GetEmotesAsync(this, Kook, options); @@ -543,11 +543,11 @@ public Task ModifyEmoteNameAsync(GuildEmote emote, Action func, RequestO /// public Task DeleteEmoteAsync(GuildEmote emote, RequestOptions options = null) => GuildHelper.DeleteEmoteAsync(this, Kook, emote.Id, options); - + #endregion #region Invites - + /// public async Task> GetInvitesAsync(RequestOptions options = null) => await GuildHelper.GetInvitesAsync(this, Kook, options).ConfigureAwait(false); @@ -559,12 +559,12 @@ public async Task CreateInviteAsync(InviteMaxAge maxAge = InviteMaxAge. => await GuildHelper.CreateInviteAsync(this, Kook, maxAge, maxUses, options).ConfigureAwait(false); #endregion - + #region IGuild - + /// bool IGuild.Available => Available; - + /// IReadOnlyCollection IGuild.Roles => Roles; @@ -573,13 +573,13 @@ public async Task CreateInviteAsync(InviteMaxAge maxAge = InviteMaxAge. /// IRecommendInfo IGuild.RecommendInfo => RecommendInfo; - + /// IRole IGuild.EveryoneRole => EveryoneRole; /// IRole IGuild.GetRole(uint id) => GetRole(id); - + /// async Task IGuild.CreateRoleAsync(string name, RequestOptions options) => await CreateRoleAsync(name, options).ConfigureAwait(false); @@ -637,7 +637,7 @@ async Task IGuild.GetUserAsync(ulong id, CacheMode mode, RequestOpti else return null; } - + /// async Task> IGuild.GetBansAsync(RequestOptions options) => await GetBansAsync(options).ConfigureAwait(false); @@ -647,7 +647,7 @@ async Task IGuild.GetBanAsync(IUser user, RequestOptions options) /// async Task IGuild.GetBanAsync(ulong userId, RequestOptions options) => await GetBanAsync(userId, options).ConfigureAwait(false); - + /// async Task> IGuild.GetChannelsAsync(CacheMode mode, RequestOptions options) { @@ -721,7 +721,7 @@ async Task> IGuild.GetCategoryChannelsAsyn else return null; } - + /// async Task IGuild.CreateTextChannelAsync(string name, Action func, RequestOptions options) => await CreateTextChannelAsync(name, func, options).ConfigureAwait(false); @@ -748,4 +748,4 @@ public async Task GetBadgeAsync(BadgeStyle style = BadgeStyle.GuildName, /// public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Id})"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Intimacies/IntimacyHelper.cs b/src/Kook.Net.Rest/Entities/Intimacies/IntimacyHelper.cs index de39b75e..97f163de 100644 --- a/src/Kook.Net.Rest/Entities/Intimacies/IntimacyHelper.cs +++ b/src/Kook.Net.Rest/Entities/Intimacies/IntimacyHelper.cs @@ -23,4 +23,4 @@ public static async Task UpdateAsync(IIntimacy intimacy, BaseKookClient client, }; await client.ApiClient.UpdateIntimacyValueAsync(args, options).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Intimacies/RestIntimacy.cs b/src/Kook.Net.Rest/Entities/Intimacies/RestIntimacy.cs index f1a673ae..e7252b2f 100644 --- a/src/Kook.Net.Rest/Entities/Intimacies/RestIntimacy.cs +++ b/src/Kook.Net.Rest/Entities/Intimacies/RestIntimacy.cs @@ -33,7 +33,7 @@ internal RestIntimacy(BaseKookClient kook, IUser user, ulong id) { User = user; } - + internal static RestIntimacy Create(BaseKookClient kook, IUser user, Model model) { var entity = new RestIntimacy(kook, user, user.Id); @@ -50,5 +50,5 @@ internal void Update(Model model) Score = model.Score; _images = model.Images.Select(i => new IntimacyImage(i.Id, i.Url)).ToImmutableArray(); } - -} \ No newline at end of file + +} diff --git a/src/Kook.Net.Rest/Entities/Invites/InviteHelper.cs b/src/Kook.Net.Rest/Entities/Invites/InviteHelper.cs index 17419166..3eab37ed 100644 --- a/src/Kook.Net.Rest/Entities/Invites/InviteHelper.cs +++ b/src/Kook.Net.Rest/Entities/Invites/InviteHelper.cs @@ -4,7 +4,7 @@ namespace Kook.Rest; internal static class InviteHelper { - public static async Task DeleteAsync(IInvite invite, BaseKookClient client, + public static async Task DeleteAsync(IInvite invite, BaseKookClient client, RequestOptions options) { DeleteGuildInviteParams args = new() @@ -15,4 +15,4 @@ public static async Task DeleteAsync(IInvite invite, BaseKookClient client, }; await client.ApiClient.DeleteGuildInviteAsync(args, options).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Invites/RestInvite.cs b/src/Kook.Net.Rest/Entities/Invites/RestInvite.cs index 38ff4702..89366851 100644 --- a/src/Kook.Net.Rest/Entities/Invites/RestInvite.cs +++ b/src/Kook.Net.Rest/Entities/Invites/RestInvite.cs @@ -35,7 +35,7 @@ public class RestInvite : RestEntity, IInvite, IUpdateable internal IChannel Channel { get; } internal IGuild Guild { get; } - + internal RestInvite(BaseKookClient kook, IGuild guild, IChannel channel, uint id) : base(kook, id) { @@ -53,7 +53,7 @@ internal void Update(Model model) Code = model.UrlCode; Url = model.Url; GuildId = model.GuildId; - ChannelId = model.ChannelId ; + ChannelId = model.ChannelId; GuildName = model.GuildName; ChannelName = model.ChannelName; ChannelType = model.ChannelType == ChannelType.Category ? ChannelType.Unspecified : model.ChannelType; @@ -64,7 +64,7 @@ internal void Update(Model model) RemainingUses = model.RemainingTimes == -1 ? null : model.RemainingTimes; Uses = MaxUses - RemainingUses; } - + /// public async Task UpdateAsync(RequestOptions options = null) { @@ -74,7 +74,7 @@ public async Task UpdateAsync(RequestOptions options = null) /// public Task DeleteAsync(RequestOptions options = null) => InviteHelper.DeleteAsync(this, Kook, options); - + /// /// Gets the URL of the invite. /// @@ -83,7 +83,7 @@ public Task DeleteAsync(RequestOptions options = null) /// public override string ToString() => Url; private string DebuggerDisplay => $"{Url} ({GuildName} / {ChannelName ?? "Channel not specified"})"; - + /// IGuild IInvite.Guild { @@ -106,4 +106,4 @@ IChannel IInvite.Channel throw new InvalidOperationException("Unable to return this entity's parent unless it was fetched through that object."); } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Messages/Attachment.cs b/src/Kook.Net.Rest/Entities/Messages/Attachment.cs index f69a42eb..0b284e11 100644 --- a/src/Kook.Net.Rest/Entities/Messages/Attachment.cs +++ b/src/Kook.Net.Rest/Entities/Messages/Attachment.cs @@ -35,7 +35,7 @@ internal Attachment(AttachmentType type, string url, string filename, int? size, Width = width; Height = height; } - + internal static Attachment Create(Model model) { AttachmentType type = model.Type switch @@ -50,7 +50,7 @@ internal static Attachment Create(Model model) : null; return new Attachment(type, model.Url, model.Name, model.Size, model.FileType, duration, model.Width, model.Height); } - + /// /// Returns the filename of this attachment. /// @@ -59,4 +59,4 @@ internal static Attachment Create(Model model) /// public override string ToString() => Filename; private string DebuggerDisplay => $"{Filename}{(Size.HasValue ? $" ({Size} bytes)" : "")}"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Messages/MessageHelper.cs b/src/Kook.Net.Rest/Entities/Messages/MessageHelper.cs index 193260c9..3bbfd001 100644 --- a/src/Kook.Net.Rest/Entities/Messages/MessageHelper.cs +++ b/src/Kook.Net.Rest/Entities/Messages/MessageHelper.cs @@ -1,11 +1,11 @@ +using Kook.API; +using Kook.API.Rest; +using Kook.Net.Converters; using System.Collections.Immutable; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; -using Kook.API; -using Kook.API.Rest; -using Kook.Net.Converters; namespace Kook.Rest; using Model = Kook.API.Message; @@ -22,7 +22,7 @@ internal static class MessageHelper /// Regex used to check if some text is formatted as a code block. /// private static readonly Regex BlockCodeRegex = new Regex(@"[^\\]?(```).+?[^\\](```)", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline); - + private static Regex PlainTextUserRegex => MentionUtils.PlainTextUserRegex; private static Regex PlainTextRoleRegex => MentionUtils.PlainTextRoleRegex; private static Regex PlainTextChannelRegex => MentionUtils.PlainTextChannelRegex; @@ -33,7 +33,7 @@ internal static class MessageHelper private static Regex KMarkdownChannelRegex => MentionUtils.KMarkdownChannelRegex; private static Regex KMarkdownEmojiRegex => Emote.KMarkdownEmojiRegex; private static Regex KMarkdownTagRegex => MentionUtils.KMarkdownTagRegex; - + public static Task DeleteAsync(IMessage msg, BaseKookClient client, RequestOptions options) => DeleteAsync(msg.Id, client, options); public static async Task DeleteAsync(Guid msgId, BaseKookClient client, @@ -49,7 +49,7 @@ public static async Task DeleteDirectAsync(Guid msgId, BaseKookClient client, { await client.ApiClient.DeleteDirectMessageAsync(msgId, options).ConfigureAwait(false); } - + public static async Task AddReactionAsync(Guid messageId, IEmote emote, BaseKookClient client, RequestOptions options) { @@ -67,7 +67,7 @@ public static async Task AddReactionAsync(IMessage msg, IEmote emote, BaseKookCl EmojiId = emote.Id, MessageId = msg.Id }; - + await client.ApiClient.AddReactionAsync(args, options).ConfigureAwait(false); } @@ -88,7 +88,7 @@ public static async Task AddDirectMessageReactionAsync(IMessage msg, IEmote emot EmojiId = emote.Id, MessageId = msg.Id }; - + await client.ApiClient.AddDirectMessageReactionAsync(args, options).ConfigureAwait(false); } @@ -104,7 +104,7 @@ public static async Task RemoveReactionAsync(Guid messageId, ulong userId, IEmot } public static async Task RemoveReactionAsync(IMessage msg, ulong userId, IEmote emote, BaseKookClient client, RequestOptions options) { - + RemoveReactionParams args = new() { EmojiId = emote.Id, @@ -126,7 +126,7 @@ public static async Task RemoveDirectMessageReactionAsync(Guid messageId, ulong } public static async Task RemoveDirectMessageReactionAsync(IMessage msg, ulong userId, IEmote emote, BaseKookClient client, RequestOptions options) { - + RemoveReactionParams args = new() { EmojiId = emote.Id, @@ -146,7 +146,7 @@ public static async Task> GetDirectMessageReactionUse var models = await client.ApiClient.GetDirectMessageReactionUsersAsync(msg.Id, emote.Id, options).ConfigureAwait(false); return models.Select(x => RestUser.Create(client, x)).ToImmutableArray(); } - + public static async Task ModifyAsync(IUserMessage msg, BaseKookClient client, Action func, RequestOptions options) { @@ -178,7 +178,7 @@ public static async Task ModifyAsync(IUserMessage msg, BaseKookClient client, Ac await ModifyAsync(msg.Id, client, json, options, args.Quote, args.EphemeralUser); return; } - + throw new NotSupportedException("Only the modification of KMarkdown and CardMessage are supported."); } @@ -195,7 +195,7 @@ public static async Task ModifyAsync(Guid msgId, BaseKookClient client, Action ParseCards(string json) } }; CardBase[] cardBases = JsonSerializer.Deserialize(json, serializerOptions); - + var cards = ImmutableArray.CreateBuilder(cardBases.Length); foreach (CardBase cardBase in cardBases) cards.Add(cardBase.ToEntity()); return cards.ToImmutable(); } - + public static string SerializeCards(IEnumerable cards) { const int maxModuleCount = 50; IEnumerable enumerable = cards as ICard[] ?? cards.ToArray(); - Preconditions.AtMost(enumerable.Sum(c => c.ModuleCount), maxModuleCount, nameof(cards), + Preconditions.AtMost(enumerable.Sum(c => c.ModuleCount), maxModuleCount, nameof(cards), $"A max of {maxModuleCount} modules are allowed."); - + CardBase[] cardBases = enumerable.Select(c => c.ToModel()).ToArray(); JsonSerializerOptions serializerOptions = new() { @@ -279,7 +279,7 @@ public static string SerializeCards(IEnumerable cards) }; return JsonSerializer.Serialize(cardBases, serializerOptions); } - + public static IReadOnlyCollection ParseAttachments(IEnumerable cards) { List attachments = new(); @@ -289,31 +289,31 @@ public static IReadOnlyCollection ParseAttachments(IEnumerable switch (module) { case FileModule fileModule: - attachments.Add(new Attachment(AttachmentType.File, fileModule.Source, fileModule.Title, + attachments.Add(new Attachment(AttachmentType.File, fileModule.Source, fileModule.Title, null, null, null, null, null)); break; case AudioModule audioModule: - attachments.Add(new Attachment(AttachmentType.Audio, audioModule.Source, audioModule.Title, + attachments.Add(new Attachment(AttachmentType.Audio, audioModule.Source, audioModule.Title, null, null, null, null, null)); break; case VideoModule videoModule: - attachments.Add(new Attachment(AttachmentType.Video, videoModule.Source, videoModule.Title, + attachments.Add(new Attachment(AttachmentType.Video, videoModule.Source, videoModule.Title, null, null, null, null, null)); break; case ContainerModule containerModule: - attachments.AddRange(containerModule.Elements.Select(x => - new Attachment(AttachmentType.Image, x.Source, x.Alternative, + attachments.AddRange(containerModule.Elements.Select(x => + new Attachment(AttachmentType.Image, x.Source, x.Alternative, null, null, null, null, null))); break; case ImageGroupModule imageGroupModule: - attachments.AddRange(imageGroupModule.Elements.Select(x => - new Attachment(AttachmentType.Image, x.Source, x.Alternative, + attachments.AddRange(imageGroupModule.Elements.Select(x => + new Attachment(AttachmentType.Image, x.Source, x.Alternative, null, null, null, null, null))); break; case ContextModule contextModule: attachments.AddRange(contextModule.Elements .OfType() - .Select(x => new Attachment(AttachmentType.Image, x.Source, x.Alternative, + .Select(x => new Attachment(AttachmentType.Image, x.Source, x.Alternative, null, null, null, null, null))); break; } @@ -342,11 +342,11 @@ bool CheckWrappedCode() // util to check if the index of a tag is within the bounds of the codeblock bool EnclosedInBlock(Match m) => m.Groups[1].Index < index && index < m.Groups[2].Index; - + // PlainText mode if (tagMode == TagMode.PlainText) return false; - + // loop through all code blocks that are before the start of the tag while (codeIndex < index) { @@ -394,7 +394,8 @@ bool EnclosedInBlock(Match m) #endif { index = match.Index; - if (CheckWrappedCode()) break; + if (CheckWrappedCode()) + break; string content = match.Groups[0].Value; if (MentionUtils.TryParseUser(content, out ulong id, tagMode)) { @@ -437,8 +438,10 @@ bool EnclosedInBlock(Match m) while (true) { index = text.IndexOf("@全体成员", index, StringComparison.Ordinal); - if (index == -1) break; - if (CheckWrappedCode()) break; + if (index == -1) + break; + if (CheckWrappedCode()) + break; var tagIndex = FindIndex(tags, index); if (tagIndex.HasValue) tags.Insert(tagIndex.Value, @@ -451,8 +454,10 @@ bool EnclosedInBlock(Match m) while (true) { index = text.IndexOf("(met)all(met)", index, StringComparison.Ordinal); - if (index == -1) break; - if (CheckWrappedCode()) break; + if (index == -1) + break; + if (CheckWrappedCode()) + break; var tagIndex = FindIndex(tags, index); if (tagIndex.HasValue) tags.Insert(tagIndex.Value, @@ -465,8 +470,10 @@ bool EnclosedInBlock(Match m) while (true) { index = text.IndexOf("@在线成员", index, StringComparison.Ordinal); - if (index == -1) break; - if (CheckWrappedCode()) break; + if (index == -1) + break; + if (CheckWrappedCode()) + break; var tagIndex = FindIndex(tags, index); if (tagIndex.HasValue) tags.Insert(tagIndex.Value, @@ -479,8 +486,10 @@ bool EnclosedInBlock(Match m) while (true) { index = text.IndexOf("(met)here(met)", index, StringComparison.Ordinal); - if (index == -1) break; - if (CheckWrappedCode()) break; + if (index == -1) + break; + if (CheckWrappedCode()) + break; var tagIndex = FindIndex(tags, index); if (tagIndex.HasValue) tags.Insert(tagIndex.Value, @@ -504,7 +513,7 @@ bool EnclosedInBlock(Match m) return null; //Overlaps tag before this return i; } - + public static MessageSource GetSource(Model msg) { if (msg.Author.Bot ?? false) @@ -531,4 +540,4 @@ public static IUser GetAuthor(BaseKookClient client, IGuild guild, UserModel mod author = RestUser.Create(client, model); return author; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Messages/Poke.cs b/src/Kook.Net.Rest/Entities/Messages/Poke.cs index a09fa2fe..1b26d272 100644 --- a/src/Kook.Net.Rest/Entities/Messages/Poke.cs +++ b/src/Kook.Net.Rest/Entities/Messages/Poke.cs @@ -66,10 +66,10 @@ internal static Poke Create(Model model) ["big"] = model.Quality.Big, }); IPokeResource pokeResource = model.Resource.ToEntity(); - return new Poke(model.Id, model.Name, model.Description, cooldown, model.Categories, label,icon, + return new Poke(model.Id, model.Name, model.Description, cooldown, model.Categories, label, icon, quality, pokeResource, model.MessageScenarios); } - + /// /// Returns the name of the poke. /// @@ -78,4 +78,4 @@ internal static Poke Create(Model model) /// public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Resource.Type})"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Messages/RestMessage.cs b/src/Kook.Net.Rest/Entities/Messages/RestMessage.cs index b3d6d171..5cf9cac1 100644 --- a/src/Kook.Net.Rest/Entities/Messages/RestMessage.cs +++ b/src/Kook.Net.Rest/Entities/Messages/RestMessage.cs @@ -1,5 +1,5 @@ -using System.Collections.Immutable; using Kook.API; +using System.Collections.Immutable; using Model = Kook.API.Message; namespace Kook.Rest; @@ -11,7 +11,7 @@ public abstract class RestMessage : RestEntity, IMessage, IUpdateable { private ImmutableArray _reactions = ImmutableArray.Create(); private ImmutableArray _userMentions = ImmutableArray.Create(); - + /// public MessageType Type { get; } @@ -29,9 +29,9 @@ public abstract class RestMessage : RestEntity, IMessage, IUpdateable /// public string CleanContent => MessageHelper.SanitizeMessage(this); - + public virtual IReadOnlyCollection Attachments { get; private set; } - + /// public DateTimeOffset Timestamp { get; private set; } /// @@ -40,7 +40,7 @@ public abstract class RestMessage : RestEntity, IMessage, IUpdateable public virtual bool? MentionedEveryone => false; /// public virtual bool? MentionedHere => false; - + /// /// Gets a collection of the 's on the message. /// @@ -63,7 +63,7 @@ public abstract class RestMessage : RestEntity, IMessage, IUpdateable public virtual IReadOnlyCollection Tags => ImmutableArray.Create(); /// public virtual bool? IsPinned => null; - + /// /// Gets the of the message. /// @@ -72,7 +72,7 @@ public abstract class RestMessage : RestEntity, IMessage, IUpdateable /// public override string ToString() => Content; - internal RestMessage(BaseKookClient kook, Guid id, MessageType messageType, + internal RestMessage(BaseKookClient kook, Guid id, MessageType messageType, IMessageChannel channel, IUser author, MessageSource source) : base(kook, id) { @@ -101,7 +101,7 @@ internal virtual void Update(Model model) Timestamp = model.CreateAt; EditedTimestamp = model.UpdateAt; Content = model.Content; - + if (model.Reactions is not null) { var value = model.Reactions; @@ -136,13 +136,13 @@ internal virtual void Update(Model model) } } - + internal virtual void Update(API.DirectMessage model) { Timestamp = model.CreateAt; EditedTimestamp = model.UpdateAt; Content = model.Content; - + if (model.Reactions is not null) { var value = model.Reactions; @@ -159,7 +159,7 @@ internal virtual void Update(API.DirectMessage model) } else _reactions = ImmutableArray.Create(); - + if (model.MentionInfo?.MentionedUsers is not null) { var value = model.MentionInfo.MentionedUsers; @@ -176,11 +176,11 @@ internal virtual void Update(API.DirectMessage model) } } } - + /// - public IReadOnlyDictionary Reactions + public IReadOnlyDictionary Reactions => _reactions.ToDictionary( - x => x.Emote, + x => x.Emote, x => new ReactionMetadata { ReactionCount = x.Count, IsMe = x.Me }); /// @@ -267,4 +267,4 @@ public Task> GetReactionUsersAsync(IEmote emote, Requ IReadOnlyCollection IMessage.MentionedUserIds => MentionedUsers.Select(x => x.Id).ToImmutableArray(); #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Messages/RestPokeAction.cs b/src/Kook.Net.Rest/Entities/Messages/RestPokeAction.cs index 4bef26db..90f952f1 100644 --- a/src/Kook.Net.Rest/Entities/Messages/RestPokeAction.cs +++ b/src/Kook.Net.Rest/Entities/Messages/RestPokeAction.cs @@ -6,7 +6,7 @@ public class RestPokeAction : IPokeAction { /// public IUser Operator { get; } - + /// public IReadOnlyCollection Targets { get; } @@ -35,4 +35,4 @@ internal static RestPokeAction Create(BaseKookClient kook, IUser @operator, IEnu /// IPoke IPokeAction.Poke => Poke; #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Messages/RestReaction.cs b/src/Kook.Net.Rest/Entities/Messages/RestReaction.cs index 183e53c6..dd1fb0d6 100644 --- a/src/Kook.Net.Rest/Entities/Messages/RestReaction.cs +++ b/src/Kook.Net.Rest/Entities/Messages/RestReaction.cs @@ -14,7 +14,7 @@ public class RestReaction : IReaction /// Gets whether the reactions is added by the user. /// public bool Me { get; } - + internal RestReaction(IEmote emote, int count, bool me) { Emote = emote; @@ -30,4 +30,4 @@ internal static RestReaction Create(Model model) emote = new Emote(model.Emoji.Id, model.Emoji.Name); return new RestReaction(emote, model.Count, model.IsMe); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Messages/RestSystemMessage.cs b/src/Kook.Net.Rest/Entities/Messages/RestSystemMessage.cs index aa89a3fd..10034c05 100644 --- a/src/Kook.Net.Rest/Entities/Messages/RestSystemMessage.cs +++ b/src/Kook.Net.Rest/Entities/Messages/RestSystemMessage.cs @@ -11,7 +11,7 @@ public class RestSystemMessage : RestMessage, ISystemMessage { /// public SystemMessageType SystemMessageType { get; set; } - + internal RestSystemMessage(BaseKookClient kook, Guid id, MessageType messageType, IMessageChannel channel, IUser author) : base(kook, id, messageType, channel, author, MessageSource.System) { @@ -33,6 +33,6 @@ internal override void Update(Model model) base.Update(model); // TODO: SystemMessageType } - + private string DebuggerDisplay => $"{Author}: {Content} ({Id}, {Type})"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Messages/RestUserMessage.cs b/src/Kook.Net.Rest/Entities/Messages/RestUserMessage.cs index 04785f67..bc576579 100644 --- a/src/Kook.Net.Rest/Entities/Messages/RestUserMessage.cs +++ b/src/Kook.Net.Rest/Entities/Messages/RestUserMessage.cs @@ -1,9 +1,9 @@ +using Kook.API; +using Kook.Net.Converters; using System.Collections.Immutable; using System.Diagnostics; using System.Text.Encodings.Web; using System.Text.Json; -using Kook.API; -using Kook.Net.Converters; using Model = Kook.API.Message; namespace Kook.Rest; @@ -25,10 +25,10 @@ public class RestUserMessage : RestMessage, IUserMessage private ImmutableArray _roleMentions = ImmutableArray.Create(); private ImmutableArray _channelMentions = ImmutableArray.Create(); private ImmutableArray _tags = ImmutableArray.Create(); - + /// public Quote Quote => _quote; - + /// public new bool? IsPinned { get; internal set; } /// @@ -55,7 +55,7 @@ public class RestUserMessage : RestMessage, IUserMessage public IReadOnlyCollection MentionedChannels => _channelMentions; /// public override IReadOnlyCollection Tags => _tags; - + internal RestUserMessage(BaseKookClient kook, Guid id, MessageType messageType, IMessageChannel channel, IUser author, MessageSource source) : base(kook, id, messageType, channel, author, source) { @@ -85,7 +85,7 @@ internal override void Update(Model model) _isMentioningEveryone = model.MentionedAll; _isMentioningHere = model.MentionedHere; _roleMentionIds = model.MentionedRoles.ToImmutableArray(); - + if (Channel is IGuildChannel guildChannel) { if (model.MentionInfo?.MentionedRoles is not null) @@ -120,7 +120,7 @@ internal override void Update(Model model) } } } - + if (model.Quote is not null) { IUser refMsgAuthor = MessageHelper.GetAuthor(Kook, null, model.Quote.Author); @@ -142,7 +142,7 @@ internal override void Update(Model model) model.MentionInfo.MentionedUsers.Select(y => RestUser.Create(Kook, y)), x)).ToImmutableArray() : ImmutableArray.Empty; } - + internal override void Update(DirectMessage model) { base.Update(model); @@ -152,7 +152,7 @@ internal override void Update(DirectMessage model) _tags = MessageHelper.ParseTags(model.Content, null, guild, MentionedUsers, TagMode.PlainText); else if (Type == MessageType.KMarkdown) _tags = MessageHelper.ParseTags(model.Content, null, guild, MentionedUsers, TagMode.KMarkdown); - + if (model.Quote is not null) { IUser refMsgAuthor = MessageHelper.GetAuthor(Kook, null, model.Quote.Author); @@ -168,7 +168,7 @@ internal override void Update(DirectMessage model) _attachments = _attachments.AddRange(MessageHelper.ParseAttachments(_cards.OfType())); } _embeds = model.Embeds.Select(x => x.ToEntity()).ToImmutableArray(); - + if (Type == MessageType.Poke && model.MentionInfo?.Pokes is not null) { IUser recipient = (Channel as IDMChannel)?.Recipient; @@ -177,13 +177,13 @@ internal override void Update(DirectMessage model) : recipient.Id == Author.Id ? Kook.CurrentUser : recipient; - _pokes = model.MentionInfo.Pokes.Select(x => RestPokeAction.Create(Kook, Author, - new [] {target}, x)).ToImmutableArray(); + _pokes = model.MentionInfo.Pokes.Select(x => RestPokeAction.Create(Kook, Author, + new[] { target }, x)).ToImmutableArray(); } else _pokes = ImmutableArray.Empty; } - + /// The zero-based index at which to begin the resolving for the specified value. /// public string Resolve(int startIndex, TagHandling userHandling = TagHandling.Name, TagHandling channelHandling = TagHandling.Name, @@ -197,7 +197,7 @@ public string Resolve(TagHandling userHandling = TagHandling.Name, TagHandling c private string DebuggerDisplay => $"{Author}: {Content} ({Id}{(Attachments is not null && Attachments.Any() ? $", {Attachments.Count} Attachment{(Attachments.Count == 1 ? string.Empty : "s")}" : string.Empty)})"; #region IUserMessage - + /// public async Task ModifyAsync(Action func, RequestOptions options = null) { @@ -211,9 +211,9 @@ public async Task ModifyAsync(Action func, RequestOptions opt func(properties); Content = properties.Content; _cards = properties.Cards?.ToImmutableArray() ?? ImmutableArray.Empty; - _quote = properties.Quote?.QuotedMessageId == Guid.Empty ? null : (Quote) properties.Quote; + _quote = properties.Quote?.QuotedMessageId == Guid.Empty ? null : (Quote)properties.Quote; } - + /// bool? IMessage.IsPinned => IsPinned; /// @@ -224,4 +224,4 @@ public async Task ModifyAsync(Action func, RequestOptions opt IReadOnlyCollection IMessage.Embeds => Embeds; #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/RestEntity.cs b/src/Kook.Net.Rest/Entities/RestEntity.cs index 8022c41d..6fefff00 100644 --- a/src/Kook.Net.Rest/Entities/RestEntity.cs +++ b/src/Kook.Net.Rest/Entities/RestEntity.cs @@ -4,7 +4,7 @@ public abstract class RestEntity : IEntity where T : IEquatable { internal BaseKookClient Kook { get; } - + /// public T Id { get; } @@ -13,4 +13,4 @@ internal RestEntity(BaseKookClient kook, T id) Kook = kook; Id = id; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Roles/RestRole.cs b/src/Kook.Net.Rest/Entities/Roles/RestRole.cs index 2509a0f7..f0c8baf8 100644 --- a/src/Kook.Net.Rest/Entities/Roles/RestRole.cs +++ b/src/Kook.Net.Rest/Entities/Roles/RestRole.cs @@ -18,7 +18,7 @@ public class RestRole : RestEntity, IRole /// An representing the parent guild of this role. /// internal IGuild Guild { get; } - + /// public RoleType? Type { get; set; } /// @@ -33,7 +33,7 @@ public class RestRole : RestEntity, IRole public GuildPermissions Permissions { get; private set; } /// public int Position { get; private set; } - + /// /// Returns a value that determines if the role is an @everyone role. /// @@ -67,7 +67,7 @@ internal void Update(Model model) Color = new Color(model.Color); Permissions = new GuildPermissions(model.Permissions); } - + /// public async Task ModifyAsync(Action func, RequestOptions options = null) { @@ -77,19 +77,19 @@ public async Task ModifyAsync(Action func, RequestOptions option /// public Task DeleteAsync(RequestOptions options = null) => RoleHelper.DeleteAsync(this, Kook, options); - + /// public IAsyncEnumerable> GetUsersAsync(RequestOptions options = null) { void Func(SearchGuildMemberProperties p) => p.RoleId = Id; return GuildHelper.SearchUsersAsync(Guild, Kook, Func, KookConfig.MaxUsersPerBatch, options); } - + /// public int CompareTo(IRole role) => RoleUtils.Compare(this, role); - + #endregion - + #region IRole /// IGuild IRole.Guild @@ -101,7 +101,7 @@ IGuild IRole.Guild throw new InvalidOperationException("Unable to return this entity's parent unless it was fetched through that object."); } } - + /// IAsyncEnumerable> IRole.GetUsersAsync(CacheMode mode, RequestOptions options) { @@ -110,9 +110,9 @@ IAsyncEnumerable> IRole.GetUsersAsync(CacheMode else return AsyncEnumerable.Empty>(); } - + #endregion - + /// /// Gets the name of the role. /// @@ -121,4 +121,4 @@ IAsyncEnumerable> IRole.GetUsersAsync(CacheMode /// public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Id})"; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Roles/RoleHelper.cs b/src/Kook.Net.Rest/Entities/Roles/RoleHelper.cs index ed976594..458bf68f 100644 --- a/src/Kook.Net.Rest/Entities/Roles/RoleHelper.cs +++ b/src/Kook.Net.Rest/Entities/Roles/RoleHelper.cs @@ -48,4 +48,4 @@ public static async Task ModifyAsync(IRole role, BaseKookClient client, } #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Users/RestGuildUser.cs b/src/Kook.Net.Rest/Entities/Users/RestGuildUser.cs index 9441ffe4..09b1e5a4 100644 --- a/src/Kook.Net.Rest/Entities/Users/RestGuildUser.cs +++ b/src/Kook.Net.Rest/Entities/Users/RestGuildUser.cs @@ -1,7 +1,7 @@ using System.Collections.Immutable; using System.Diagnostics; -using UserModel = Kook.API.User; using MemberModel = Kook.API.Rest.GuildMember; +using UserModel = Kook.API.User; namespace Kook.Rest; @@ -14,7 +14,7 @@ public class RestGuildUser : RestUser, IGuildUser #region RestGuildUser private ImmutableArray _roleIds; - + /// public string DisplayName => Nickname ?? Username; /// @@ -24,7 +24,7 @@ public class RestGuildUser : RestUser, IGuildUser public ulong GuildId => Guild.Id; /// public bool IsMobileVerified { get; private set; } - + /// public DateTimeOffset JoinedAt { get; private set; } /// @@ -33,7 +33,7 @@ public class RestGuildUser : RestUser, IGuildUser public Color Color { get; private set; } /// public bool? IsOwner { get; set; } - + /// /// Resolving permissions requires the parent guild to be downloaded. public GuildPermissions GuildPermissions @@ -47,10 +47,10 @@ public GuildPermissions GuildPermissions } /// public IReadOnlyCollection RoleIds => _roleIds; - + /// public new string PlainTextMention => MentionUtils.PlainTextMentionUser(Nickname ?? Username, Id); - + internal RestGuildUser(BaseKookClient kook, IGuild guild, ulong id) : base(kook, id) { @@ -96,13 +96,13 @@ public override async Task UpdateAsync(RequestOptions options = null) var model = await Kook.ApiClient.GetGuildMemberAsync(GuildId, Id, options).ConfigureAwait(false); Update(model); } - + /// public async Task ModifyNicknameAsync(string name, RequestOptions options = null) { var nickname = await UserHelper.ModifyNicknameAsync(this, Kook, name, options); // The KOOK API will clear the nickname if the nickname is set to the same as the username at present. - if(nickname == Username) + if (nickname == Username) nickname = null; Nickname = nickname; } @@ -169,21 +169,21 @@ public Task RemoveRolesAsync(IEnumerable roleIds, RequestOptions options = public Task RemoveRolesAsync(IEnumerable roles, RequestOptions options = null) => RemoveRolesAsync(roles.Select(x => x.Id)); /// - public Task MuteAsync(RequestOptions options = null) + public Task MuteAsync(RequestOptions options = null) => GuildHelper.MuteUserAsync(this, Kook, options); /// - public Task DeafenAsync(RequestOptions options = null) + public Task DeafenAsync(RequestOptions options = null) => GuildHelper.DeafenUserAsync(this, Kook, options); /// - public Task UnmuteAsync(RequestOptions options = null) + public Task UnmuteAsync(RequestOptions options = null) => GuildHelper.UnmuteUserAsync(this, Kook, options); /// - public Task UndeafenAsync(RequestOptions options = null) + public Task UndeafenAsync(RequestOptions options = null) => GuildHelper.UndeafenUserAsync(this, Kook, options); /// public Task> GetConnectedVoiceChannelsAsync(RequestOptions options = null) => UserHelper.GetConnectedChannelAsync(this, Kook, options); - + /// /// Resolving permissions requires the parent guild to be downloaded. public ChannelPermissions GetPermissions(IGuildChannel channel) @@ -191,9 +191,9 @@ public ChannelPermissions GetPermissions(IGuildChannel channel) var guildPerms = GuildPermissions; return new ChannelPermissions(Permissions.ResolveChannel(Guild, this, channel, guildPerms.RawValue)); } - + #endregion - + #region IGuildUser /// IGuild IGuildUser.Guild @@ -206,15 +206,15 @@ IGuild IGuildUser.Guild } } #endregion - + #region IVoiceState - + /// bool? IVoiceState.IsMuted => null; /// bool? IVoiceState.IsDeafened => null; /// IVoiceChannel IVoiceState.VoiceChannel => null; - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Users/RestPresence.cs b/src/Kook.Net.Rest/Entities/Users/RestPresence.cs index ebee9976..abf49c5e 100644 --- a/src/Kook.Net.Rest/Entities/Users/RestPresence.cs +++ b/src/Kook.Net.Rest/Entities/Users/RestPresence.cs @@ -52,8 +52,8 @@ internal void Update(bool? isOnline, string activeClient) return type; return null; } - - private string DebuggerDisplay => $"{IsOnline switch {true => "Online", false => "Offline", _ => "Unknown Status"}}{ActiveClient.ToString()}"; + + private string DebuggerDisplay => $"{IsOnline switch { true => "Online", false => "Offline", _ => "Unknown Status" }}{ActiveClient.ToString()}"; internal RestPresence Clone() => MemberwiseClone() as RestPresence; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Users/RestSelfUser.cs b/src/Kook.Net.Rest/Entities/Users/RestSelfUser.cs index 19d66e7d..a561f28c 100644 --- a/src/Kook.Net.Rest/Entities/Users/RestSelfUser.cs +++ b/src/Kook.Net.Rest/Entities/Users/RestSelfUser.cs @@ -17,7 +17,7 @@ public class RestSelfUser : RestUser, ISelfUser public int InvitedCount { get; private set; } /// public bool IsMobileVerified { get; private set; } - + internal RestSelfUser(BaseKookClient kook, ulong id) : base(kook, id) { @@ -31,13 +31,13 @@ internal static RestSelfUser Create(BaseKookClient kook, Model model) internal void Update(Model model) { base.Update(model); - + MobilePrefix = model.MobilePrefix; Mobile = model.Mobile; InvitedCount = model.InvitedCount ?? 0; IsMobileVerified = model.MobileVerified; } - + /// /// Unable to update this object using a different token. public override async Task UpdateAsync(RequestOptions options = null) @@ -49,7 +49,7 @@ public override async Task UpdateAsync(RequestOptions options = null) } #region ISelfUser - + /// public async Task StartPlayingAsync(IGame game, RequestOptions options = null) { @@ -67,4 +67,4 @@ public async Task StopPlayingAsync(ActivityType type, RequestOptions options = n } #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Users/RestUser.cs b/src/Kook.Net.Rest/Entities/Users/RestUser.cs index aa646bcf..565f9e8a 100644 --- a/src/Kook.Net.Rest/Entities/Users/RestUser.cs +++ b/src/Kook.Net.Rest/Entities/Users/RestUser.cs @@ -1,7 +1,7 @@ -using System.Diagnostics; -using System.Globalization; using Kook.API; using Kook.WebSocket; +using System.Diagnostics; +using System.Globalization; using Model = Kook.API.User; namespace Kook.Rest; @@ -13,7 +13,7 @@ namespace Kook.Rest; public class RestUser : RestEntity, IUser, IUpdateable { #region RestUser - + /// public string Username { get; internal set; } /// @@ -41,13 +41,13 @@ public class RestUser : RestEntity, IUser, IUpdateable public string KMarkdownMention => MentionUtils.KMarkdownMentionUser(Id); /// public string PlainTextMention => MentionUtils.PlainTextMentionUser(Username, Id); - + internal RestPresence Presence { get; set; } /// public bool? IsOnline => Presence?.IsOnline; /// public ClientType? ActiveClient => Presence?.ActiveClient; - + internal RestUser(BaseKookClient kook, ulong id) : base(kook, id) { @@ -79,7 +79,7 @@ internal virtual void Update(Model model) BuffAvatar = model.BuffAvatar; IsDenoiseEnabled = model.IsDenoiseEnabled; UserTag = model.UserTag?.ToEntity(); - + UpdatePresence(model.Online, model.OperatingSystem); } @@ -134,7 +134,7 @@ public async Task UpdateIntimacyAsync(Action func, RequestOp await UserHelper.UpdateIntimacyAsync(this, Kook, func, options).ConfigureAwait(false); } #endregion - + /// /// Gets the Username#IdentifyNumber of the user. /// @@ -144,16 +144,16 @@ public async Task UpdateIntimacyAsync(Action func, RequestOp public override string ToString() => Format.UsernameAndIdentifyNumber(this); private string DebuggerDisplay => $"{Format.UsernameAndIdentifyNumber(this)} ({Id}{(IsBot ?? false ? ", Bot" : "")})"; - - + + #region IUser - + /// async Task IUser.CreateDMChannelAsync(RequestOptions options) => await CreateDMChannelAsync(options).ConfigureAwait(false); /// async Task IUser.GetIntimacyAsync(RequestOptions options) => await GetIntimacyAsync(options).ConfigureAwait(false); - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Entities/Users/UserHelper.cs b/src/Kook.Net.Rest/Entities/Users/UserHelper.cs index 4e778dbb..e3ae9f49 100644 --- a/src/Kook.Net.Rest/Entities/Users/UserHelper.cs +++ b/src/Kook.Net.Rest/Entities/Users/UserHelper.cs @@ -110,4 +110,4 @@ public static async Task UpdateIntimacyAsync(IUser user, BaseKookClient client, }; await client.ApiClient.UpdateIntimacyValueAsync(args, options).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Extensions/EntityExtensions.cs b/src/Kook.Net.Rest/Extensions/EntityExtensions.cs index e7392155..7774416a 100644 --- a/src/Kook.Net.Rest/Extensions/EntityExtensions.cs +++ b/src/Kook.Net.Rest/Extensions/EntityExtensions.cs @@ -1,7 +1,7 @@ +using Kook.API; using System.Collections.Immutable; using System.Reflection; using System.Text.Json; -using Kook.API; namespace Kook.Rest; @@ -17,12 +17,13 @@ public static GuildEmote ToEntity(this API.Emoji model, ulong guildId) model.UploadedBy?.Id); #endregion - + #region Elements public static IElement ToEntity(this API.ElementBase model) { - if (model is null) return null; + if (model is null) + return null; return model.Type switch { ElementType.PlainText => (model as API.PlainTextElement).ToEntity(), @@ -35,33 +36,39 @@ public static IElement ToEntity(this API.ElementBase model) } public static PlainTextElement ToEntity(this API.PlainTextElement model) { - if (model is null) return null; + if (model is null) + return null; return new PlainTextElement(model.Content, model.Emoji); } public static KMarkdownElement ToEntity(this API.KMarkdownElement model) { - if (model is null) return null; + if (model is null) + return null; return new KMarkdownElement(model.Content); } public static ImageElement ToEntity(this API.ImageElement model) { - if (model is null) return null; + if (model is null) + return null; return new ImageElement(model.Source, model.Alternative, model.Size, model.Circle); } public static ButtonElement ToEntity(this API.ButtonElement model) { - if (model is null) return null; + if (model is null) + return null; return new ButtonElement(model.Theme, model.Value, model.Click, model.Text.ToEntity()); } public static ParagraphStruct ToEntity(this API.ParagraphStruct model) { - if (model is null) return null; + if (model is null) + return null; return new ParagraphStruct(model.ColumnCount, model.Fields.Select(e => e.ToEntity()).ToImmutableArray()); } public static API.ElementBase ToModel(this IElement entity) { - if (entity is null) return null; + if (entity is null) + return null; return entity.Type switch { ElementType.PlainText => (entity as PlainTextElement).ToModel(), @@ -74,7 +81,8 @@ public static API.ElementBase ToModel(this IElement entity) } public static API.PlainTextElement ToModel(this PlainTextElement entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.PlainTextElement { Content = entity.Content, @@ -84,7 +92,8 @@ public static API.PlainTextElement ToModel(this PlainTextElement entity) } public static API.KMarkdownElement ToModel(this KMarkdownElement entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.KMarkdownElement() { Content = entity.Content, @@ -93,7 +102,8 @@ public static API.KMarkdownElement ToModel(this KMarkdownElement entity) } public static API.ImageElement ToModel(this ImageElement entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.ImageElement() { Alternative = entity.Alternative, @@ -105,7 +115,8 @@ public static API.ImageElement ToModel(this ImageElement entity) } public static API.ButtonElement ToModel(this ButtonElement entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.ButtonElement() { Click = entity.Click, @@ -117,7 +128,8 @@ public static API.ButtonElement ToModel(this ButtonElement entity) } public static API.ParagraphStruct ToModel(this ParagraphStruct entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.ParagraphStruct() { ColumnCount = entity.ColumnCount, @@ -132,8 +144,10 @@ public static API.ParagraphStruct ToModel(this ParagraphStruct entity) public static IModule ToEntity(this API.ModuleBase model) { - if (model is null) return null; - if (model is null) return null; + if (model is null) + return null; + if (model is null) + return null; return model.Type switch { ModuleType.Header => (model as API.HeaderModule).ToEntity(), @@ -154,69 +168,82 @@ public static IModule ToEntity(this API.ModuleBase model) public static HeaderModule ToEntity(this API.HeaderModule model) { - if (model is null) return null; + if (model is null) + return null; return new HeaderModule(model.Text.ToEntity()); } public static SectionModule ToEntity(this API.SectionModule model) { - if (model is null) return null; + if (model is null) + return null; return new SectionModule(model.Mode, model.Text.ToEntity(), model.Accessory.ToEntity()); } public static ImageGroupModule ToEntity(this API.ImageGroupModule model) { - if (model is null) return null; + if (model is null) + return null; return new ImageGroupModule(model.Elements.Select(e => e.ToEntity()).ToImmutableArray()); } public static ContainerModule ToEntity(this API.ContainerModule model) { - if (model is null) return null; + if (model is null) + return null; return new ContainerModule(model.Elements.Select(e => e.ToEntity()).ToImmutableArray()); } public static ActionGroupModule ToEntity(this API.ActionGroupModule model) { - if (model is null) return null; + if (model is null) + return null; return new ActionGroupModule(model.Elements.Select(e => e.ToEntity()).ToImmutableArray()); } public static ContextModule ToEntity(this API.ContextModule model) { - if (model is null) return null; + if (model is null) + return null; return new ContextModule(model.Elements.Select(e => e.ToEntity()).ToImmutableArray()); } public static DividerModule ToEntity(this API.DividerModule model) { - if (model is null) return null; + if (model is null) + return null; return new DividerModule(); } public static FileModule ToEntity(this API.FileModule model) { - if (model is null) return null; + if (model is null) + return null; return new FileModule(model.Source, model.Title); } public static AudioModule ToEntity(this API.AudioModule model) { - if (model is null) return null; + if (model is null) + return null; return new AudioModule(model.Source, model.Title, model.Cover); } public static VideoModule ToEntity(this API.VideoModule model) { - if (model is null) return null; + if (model is null) + return null; return new VideoModule(model.Source, model.Title); } public static CountdownModule ToEntity(this API.CountdownModule model) { - if (model is null) return null; + if (model is null) + return null; return new CountdownModule(model.Mode, model.EndTime, model.StartTime); } public static InviteModule ToEntity(this API.InviteModule model) { - if (model is null) return null; + if (model is null) + return null; return new InviteModule(model.Code); } public static API.ModuleBase ToModel(this IModule entity) { - if (entity is null) return null; + if (entity is null) + return null; return entity.Type switch { ModuleType.Header => (entity as HeaderModule).ToModel(), @@ -236,7 +263,8 @@ public static API.ModuleBase ToModel(this IModule entity) } public static API.HeaderModule ToModel(this HeaderModule entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.HeaderModule() { Text = entity.Text.ToModel(), @@ -245,7 +273,8 @@ public static API.HeaderModule ToModel(this HeaderModule entity) } public static API.SectionModule ToModel(this SectionModule entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.SectionModule() { Accessory = entity.Accessory.ToModel(), @@ -256,7 +285,8 @@ public static API.SectionModule ToModel(this SectionModule entity) } public static API.ImageGroupModule ToModel(this ImageGroupModule entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.ImageGroupModule() { Elements = entity.Elements.Select(e => e.ToModel()).ToArray(), @@ -265,7 +295,8 @@ public static API.ImageGroupModule ToModel(this ImageGroupModule entity) } public static API.ContainerModule ToModel(this ContainerModule entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.ContainerModule() { Elements = entity.Elements.Select(e => e.ToModel()).ToArray(), @@ -274,7 +305,8 @@ public static API.ContainerModule ToModel(this ContainerModule entity) } public static API.ActionGroupModule ToModel(this ActionGroupModule entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.ActionGroupModule() { Elements = entity.Elements.Select(e => e.ToModel()).ToArray(), @@ -283,7 +315,8 @@ public static API.ActionGroupModule ToModel(this ActionGroupModule entity) } public static API.ContextModule ToModel(this ContextModule entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.ContextModule() { Elements = entity.Elements.Select(e => e.ToModel()).ToArray(), @@ -292,7 +325,8 @@ public static API.ContextModule ToModel(this ContextModule entity) } public static API.DividerModule ToModel(this DividerModule entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.DividerModule() { Type = entity.Type @@ -300,7 +334,8 @@ public static API.DividerModule ToModel(this DividerModule entity) } public static API.FileModule ToModel(this FileModule entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.FileModule() { Source = entity.Source, @@ -310,7 +345,8 @@ public static API.FileModule ToModel(this FileModule entity) } public static API.AudioModule ToModel(this AudioModule entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.AudioModule() { Cover = entity.Cover, @@ -321,7 +357,8 @@ public static API.AudioModule ToModel(this AudioModule entity) } public static API.VideoModule ToModel(this VideoModule entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.VideoModule() { Source = entity.Source, @@ -331,7 +368,8 @@ public static API.VideoModule ToModel(this VideoModule entity) } public static API.CountdownModule ToModel(this CountdownModule entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.CountdownModule() { Mode = entity.Mode, @@ -342,36 +380,40 @@ public static API.CountdownModule ToModel(this CountdownModule entity) } public static API.InviteModule ToModel(this InviteModule entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.InviteModule() { Code = entity.Code, Type = entity.Type }; } - + #endregion #region Cards public static ICard ToEntity(this API.CardBase model) { - if (model is null) return null; + if (model is null) + return null; return model.Type switch { - CardType.Card => (model as API.Card).ToEntity(), + CardType.Card => (model as API.Card).ToEntity(), _ => throw new ArgumentOutOfRangeException(nameof(API.CardBase)) }; } public static Card ToEntity(this API.Card model) { - if (model is null) return null; + if (model is null) + return null; return new Card(model.Theme, model.Size, model.Color, model.Modules.Select(m => m.ToEntity()).ToImmutableArray()); } - + public static API.CardBase ToModel(this ICard entity) { - if (entity is null) return null; + if (entity is null) + return null; return entity.Type switch { CardType.Card => (entity as Card).ToModel(), @@ -380,7 +422,8 @@ public static API.CardBase ToModel(this ICard entity) } public static API.Card ToModel(this Card entity) { - if (entity is null) return null; + if (entity is null) + return null; return new API.Card() { Theme = entity.Theme, @@ -394,10 +437,11 @@ public static API.Card ToModel(this Card entity) #endregion #region Embeds - + public static IEmbed ToEntity(this API.EmbedBase model) { - if (model is null) return null; + if (model is null) + return null; return model.Type switch { EmbedType.Link => (model as API.LinkEmbed).ToEntity(), @@ -430,7 +474,8 @@ public static BilibiliVideoEmbed ToEntity(this API.BilibiliVideoEmbed model) public static IPokeResource ToEntity(this API.PokeResourceBase model) { - if (model is null) return null; + if (model is null) + return null; return model.Type switch { PokeResourceType.ImageAnimation => (model as API.ImageAnimationPokeResource).ToEntity(), @@ -450,7 +495,7 @@ public static ImageAnimationPokeResource ToEntity(this API.ImageAnimationPokeRes }, TimeSpan.FromMilliseconds(model.Duration), model.Width, model.Height, model.Percent / 100D); #endregion - + #region Overwrites public static UserPermissionOverwrite ToEntity(this API.UserPermissionOverwrite model) @@ -465,10 +510,11 @@ public static RolePermissionOverwrite ToEntity(this API.RolePermissionOverwrite #endregion #region Recommendation Infos - + public static RecommendInfo ToEntity(this API.RecommendInfo model) { - if (model is null) return null; + if (model is null) + return null; return RecommendInfo.Create(model); } @@ -478,9 +524,10 @@ public static RecommendInfo ToEntity(this API.RecommendInfo model) public static UserTag ToEntity(this API.UserTag model) { - if (model is null) return null; + if (model is null) + return null; return UserTag.Create(model.Color, model.Text); } #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/KookRestApiClient.cs b/src/Kook.Net.Rest/KookRestApiClient.cs index 4b5c2509..461bfa5a 100644 --- a/src/Kook.Net.Rest/KookRestApiClient.cs +++ b/src/Kook.Net.Rest/KookRestApiClient.cs @@ -1,6 +1,13 @@ +using Kook.API; +using Kook.API.Rest; +using Kook.Net; +using Kook.Net.Converters; +using Kook.Net.Queue; +using Kook.Net.Rest; using System.Collections.Concurrent; using System.Diagnostics; using System.Globalization; +using System.Linq; using System.Linq.Expressions; using System.Net; using System.Net.Http.Headers; @@ -8,22 +15,15 @@ using System.Text; using System.Text.Encodings.Web; using System.Text.Json; -using Kook.API; -using Kook.Net; -using Kook.Net.Queue; -using Kook.Net.Rest; -using System.Linq; using System.Text.Json.Serialization; using System.Web; -using Kook.API.Rest; -using Kook.Net.Converters; namespace Kook.API; internal class KookRestApiClient : IDisposable { #region KookRestApiClient - + private static readonly ConcurrentDictionary> _bucketIdGenerators = new ConcurrentDictionary>(); public event Func SentRequest { add => _sentRequestEvent.Add(value); remove => _sentRequestEvent.Remove(value); } @@ -38,7 +38,7 @@ internal class KookRestApiClient : IDisposable public RetryMode DefaultRetryMode { get; } public string UserAgent { get; } - + internal RequestQueue RequestQueue { get; } public LoginState LoginState { get; internal set; } public TokenType AuthTokenType { get; set; } @@ -46,7 +46,7 @@ internal class KookRestApiClient : IDisposable internal IRestClient RestClient { get; private set; } internal ulong? CurrentUserId { get; set; } internal Func DefaultRatelimitCallback { get; set; } - + public KookRestApiClient(RestClientProvider restClientProvider, string userAgent, string acceptLanguage = null, RetryMode defaultRetryMode = RetryMode.AlwaysRetry, JsonSerializerOptions serializerOptions = null, Func defaultRatelimitCallback = null) { @@ -59,7 +59,7 @@ public KookRestApiClient(RestClientProvider restClientProvider, string userAgent NumberHandling = JsonNumberHandling.AllowReadingFromString }; DefaultRatelimitCallback = defaultRatelimitCallback; - + RequestQueue = new RequestQueue(); _stateLock = new SemaphoreSlim(1, 1); SetBaseUrl(KookConfig.APIUrl); @@ -95,7 +95,7 @@ internal virtual void Dispose(bool disposing) } } public void Dispose() => Dispose(true); - + public async Task LoginAsync(TokenType tokenType, string token) { await _stateLock.WaitAsync().ConfigureAwait(false); @@ -116,7 +116,7 @@ private async Task LoginInternalAsync(TokenType tokenType, string token) { _loginCancelToken?.Dispose(); _loginCancelToken = new CancellationTokenSource(); - + AuthToken = null; await RequestQueue.SetCancelTokenAsync(_loginCancelToken.Token).ConfigureAwait(false); RestClient.SetCancelToken(_loginCancelToken.Token); @@ -133,7 +133,7 @@ private async Task LoginInternalAsync(TokenType tokenType, string token) throw; } } - + public async Task LogoutAsync() { await _stateLock.WaitAsync().ConfigureAwait(false); @@ -146,10 +146,12 @@ public async Task LogoutAsync() private async Task LogoutInternalAsync() { //An exception here will lock the client into the unusable LoggingOut state, but that's probably fine since our client is in an undefined state too. - if (LoginState == LoginState.LoggedOut) return; + if (LoginState == LoginState.LoggedOut) + return; LoginState = LoginState.LoggingOut; - try { _loginCancelToken?.Cancel(false); } + try + { _loginCancelToken?.Cancel(false); } catch { // ignored @@ -166,11 +168,11 @@ private async Task LogoutInternalAsync() } internal virtual Task ConnectInternalAsync() => Task.Delay(0); internal virtual Task DisconnectInternalAsync(Exception ex = null) => Task.Delay(0); - + #endregion #region Core - + internal Task SendAsync(HttpMethod method, Expression> endpointExpr, BucketIds ids, ClientBucketType clientBucket = ClientBucketType.Unbucketed, RequestOptions options = null, [CallerMemberName] string funcName = null) => SendAsync(method, GetEndpoint(endpointExpr), GetBucketId(method, ids, endpointExpr, funcName), clientBucket, options); @@ -222,7 +224,7 @@ public async Task SendAsync(HttpMethod method, string endp { options ??= new RequestOptions(); options.BucketId = bucketId; - + var request = new RestRequest(RestClient, method, endpoint, options); Stream response = await SendInternalAsync(method, endpoint, request).ConfigureAwait(false); return bypassDeserialization ? response as TResponse : await DeserializeJsonAsync(response).ConfigureAwait(false); @@ -236,9 +238,9 @@ public async Task SendJsonAsync(HttpMethod method, string { options ??= new RequestOptions(); options.BucketId = bucketId; - + string json = payload != null ? SerializeJson(payload) : null; - + var request = new JsonRestRequest(RestClient, method, endpoint, json, options); Stream response = await SendInternalAsync(method, endpoint, request).ConfigureAwait(false); return bypassDeserialization ? response as TResponse : await DeserializeJsonAsync(response).ConfigureAwait(false); @@ -257,7 +259,7 @@ public async Task SendMultipartAsync(HttpMethod method, st Stream response = await SendInternalAsync(method, endpoint, request).ConfigureAwait(false); return bypassDeserialization ? response as TResponse : await DeserializeJsonAsync(response).ConfigureAwait(false); } - + private async Task SendInternalAsync(HttpMethod method, string endpoint, RestRequest request) { if (!request.Options.IgnoreState) @@ -265,29 +267,29 @@ private async Task SendInternalAsync(HttpMethod method, string endpoint, request.Options.RetryMode ??= DefaultRetryMode; request.Options.RatelimitCallback ??= DefaultRatelimitCallback; - + var stopwatch = Stopwatch.StartNew(); var responseStream = await RequestQueue.SendAsync(request).ConfigureAwait(false); stopwatch.Stop(); - + double milliseconds = ToMilliseconds(stopwatch); await _sentRequestEvent.InvokeAsync(method, endpoint, milliseconds).ConfigureAwait(false); - + return responseStream; } - + /// /// /// $"endpoint?params=args&page_size={pageSize}&page={page}" /// /// - internal async IAsyncEnumerable> SendPagedAsync(HttpMethod method, + internal async IAsyncEnumerable> SendPagedAsync(HttpMethod method, Expression> endpointExpr, BucketIds ids, ClientBucketType clientBucket = ClientBucketType.Unbucketed, PageMeta pageMeta = null, RequestOptions options = null) where T : class { pageMeta ??= PageMeta.Default; - + while (pageMeta.Page <= pageMeta.PageTotal) { PagedResponseBase pagedResp = await SendAsync, int, int>( @@ -307,43 +309,43 @@ internal async IAsyncEnumerable> SendPagedAsync(HttpMe public async Task> ListGuildsAsync(RequestOptions options = null) { options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); - return await SendAsync>(HttpMethod.Get, + return await SendAsync>(HttpMethod.Get, () => $"guild/index", ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } public IAsyncEnumerable> GetGuildsAsync(int limit = KookConfig.MaxItemsPerBatchByDefault, int fromPage = 1, RequestOptions options = null) { options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); return SendPagedAsync(HttpMethod.Get, (pageSize, page) => $"guild/list?page_size={pageSize}&page={page}", ids, clientBucket: ClientBucketType.SendEdit, pageMeta: new PageMeta(page: fromPage, pageSize: limit), options: options); } - + public async Task GetGuildAsync(ulong guildId, RequestOptions options = null) { Preconditions.NotEqual(guildId, 0, nameof(guildId)); options = RequestOptions.CreateOrClone(options); var ids = new BucketIds(guildId: guildId); - return await SendAsync(HttpMethod.Get, + return await SendAsync(HttpMethod.Get, () => $"guild/view?guild_id={guildId}", ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async ValueTask GetGuildMemberCountAsync(ulong guildId, RequestOptions options = null) { Preconditions.NotEqual(guildId, 0, nameof(guildId)); options = RequestOptions.CreateOrClone(options); var ids = new BucketIds(guildId: guildId); - var response = await SendAsync(HttpMethod.Get, + var response = await SendAsync(HttpMethod.Get, () => $"guild/user-list?guild_id={guildId}", ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); return response.UserCount; } - + public IAsyncEnumerable> GetGuildMembersAsync(ulong guildId, Action func = null, int limit = KookConfig.MaxUsersPerBatch, int fromPage = 1, RequestOptions options = null) { @@ -351,17 +353,22 @@ public IAsyncEnumerable> GetGuildMembersAsync(u Preconditions.GreaterThan(limit, 0, nameof(limit)); Preconditions.AtMost(limit, KookConfig.MaxUsersPerBatch, nameof(limit)); options = RequestOptions.CreateOrClone(options); - + string extendedQuery = string.Empty; if (func is not null) { SearchGuildMemberProperties properties = new(); func(properties); - if (!string.IsNullOrWhiteSpace(properties.SearchName)) extendedQuery += $"&search={Uri.EscapeDataString(properties.SearchName)}"; - if (properties.RoleId.HasValue) extendedQuery += $"&role_id={properties.RoleId.Value}"; - if (properties.IsMobileVerified.HasValue) extendedQuery += $"&mobile_verified={properties.IsMobileVerified.Value switch {true => 1, false => 0}}"; - if (properties.SortedByActiveTime.HasValue) extendedQuery += $"&active_time={(int)properties.SortedByActiveTime.Value}"; - if (properties.SortedByJoinTime.HasValue) extendedQuery += $"&joined_at={(int)properties.SortedByJoinTime.Value}"; + if (!string.IsNullOrWhiteSpace(properties.SearchName)) + extendedQuery += $"&search={Uri.EscapeDataString(properties.SearchName)}"; + if (properties.RoleId.HasValue) + extendedQuery += $"&role_id={properties.RoleId.Value}"; + if (properties.IsMobileVerified.HasValue) + extendedQuery += $"&mobile_verified={properties.IsMobileVerified.Value switch { true => 1, false => 0 }}"; + if (properties.SortedByActiveTime.HasValue) + extendedQuery += $"&active_time={(int)properties.SortedByActiveTime.Value}"; + if (properties.SortedByJoinTime.HasValue) + extendedQuery += $"&joined_at={(int)properties.SortedByJoinTime.Value}"; } var ids = new BucketIds(guildId: guildId); return SendPagedAsync(HttpMethod.Get, (pageSize, page) => $"guild/user-list?guild_id={guildId}&page_size={pageSize}&page={page}{extendedQuery}", @@ -410,7 +417,7 @@ public async Task GetGuildMutedDeafenedUsersAsync( { Preconditions.NotEqual(guildId, 0, nameof(guildId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(guildId: guildId); return await SendAsync(HttpMethod.Get, () => $"guild-mute/list?guild_id={guildId}&return_type=detail", ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -421,7 +428,7 @@ public async Task CreateGuildMuteDeafAsync(CreateOrRemoveGuildMuteDeafParams arg Preconditions.NotEqual(args.GuildId, 0, nameof(args.GuildId)); Preconditions.NotEqual(args.UserId, 0, nameof(args.UserId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(guildId: args.GuildId); await SendJsonAsync(HttpMethod.Post, () => $"guild-mute/create", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -432,7 +439,7 @@ public async Task RemoveGuildMuteDeafAsync(CreateOrRemoveGuildMuteDeafParams arg Preconditions.NotEqual(args.GuildId, 0, nameof(args.GuildId)); Preconditions.NotEqual(args.UserId, 0, nameof(args.UserId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(guildId: args.GuildId); await SendJsonAsync(HttpMethod.Post, () => $"guild-mute/delete", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -443,10 +450,12 @@ public IAsyncEnumerable> GetGuildBoostSub { Preconditions.NotEqual(guildId, 0, nameof(guildId)); string query = $"guild_id={guildId}"; - if (since.HasValue) query += $"&start_time={since.Value.ToUnixTimeSeconds()}"; - if (until.HasValue) query += $"&end_time={until.Value.ToUnixTimeSeconds()}"; + if (since.HasValue) + query += $"&start_time={since.Value.ToUnixTimeSeconds()}"; + if (until.HasValue) + query += $"&end_time={until.Value.ToUnixTimeSeconds()}"; options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(guildId: guildId); return SendPagedAsync(HttpMethod.Get, (pageSize, page) => $"guild-boost/history?{query}&page_size={pageSize}&page={page}", ids, clientBucket: ClientBucketType.SendEdit, pageMeta: new PageMeta(page: fromPage, pageSize: limit), options: options); @@ -471,11 +480,11 @@ public async Task GetGuildChannelAsync(ulong channelId, RequestOptions { Preconditions.NotEqual(channelId, 0, nameof(channelId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(channelId: channelId); return await SendAsync(HttpMethod.Get, () => $"channel/view?target_id={channelId}", ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task ModifyGuildChannelAsync(ulong channelId, ModifyGuildChannelParams args, RequestOptions options = null) { Preconditions.NotEqual(channelId, 0, nameof(channelId)); @@ -488,7 +497,7 @@ public async Task ModifyGuildChannelAsync(ulong channelId, ModifyGuildC var ids = new BucketIds(channelId: channelId); return await SendJsonAsync(HttpMethod.Post, () => $"channel/update", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task ModifyGuildChannelAsync(ulong channelId, ModifyTextChannelParams args, RequestOptions options = null) { Preconditions.NotEqual(channelId, 0, nameof(channelId)); @@ -501,7 +510,7 @@ public async Task ModifyGuildChannelAsync(ulong channelId, ModifyTextCh var ids = new BucketIds(channelId: channelId); return await SendJsonAsync(HttpMethod.Post, () => $"channel/update", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task ModifyGuildChannelAsync(ulong channelId, ModifyVoiceChannelParams args, RequestOptions options = null) { Preconditions.NotEqual(channelId, 0, nameof(channelId)); @@ -515,7 +524,7 @@ public async Task ModifyGuildChannelAsync(ulong channelId, ModifyVoiceC var ids = new BucketIds(channelId: channelId); return await SendJsonAsync(HttpMethod.Post, () => $"channel/update", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task CreateGuildChannelAsync(CreateGuildChannelParams args, RequestOptions options = null) { Preconditions.NotNull(args, nameof(args)); @@ -523,7 +532,7 @@ public async Task CreateGuildChannelAsync(CreateGuildChannelParams args Preconditions.AtLeast(args.LimitAmount, 0, nameof(args.LimitAmount)); Preconditions.AtMost(args.LimitAmount, 99, nameof(args.LimitAmount)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(guildId: args.GuildId); return await SendJsonAsync(HttpMethod.Post, () => $"channel/create", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -533,7 +542,7 @@ public async Task DeleteGuildChannelAsync(DeleteGuildChannelParams args, Request Preconditions.NotNull(args, nameof(args)); Preconditions.NotEqual(args.ChannelId, 0, nameof(args.ChannelId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(channelId: args.ChannelId); await SendJsonAsync(HttpMethod.Post, () => $"channel/delete", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -543,7 +552,7 @@ public async Task MoveUsersAsync(MoveUsersParams args, RequestOptions options = Preconditions.NotNull(args, nameof(args)); Preconditions.NotEqual(args.ChannelId, 0, nameof(args.ChannelId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(channelId: args.ChannelId); await SendJsonAsync(HttpMethod.Post, () => $"channel/move-user", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -552,7 +561,7 @@ public async Task> GetConnectedUsersAsync(ulong channe { Preconditions.NotEqual(channelId, 0, nameof(channelId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(channelId: channelId); return await SendAsync>(HttpMethod.Get, () => $"channel/user-list?channel_id={channelId}", ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -565,7 +574,7 @@ public async Task GetChannelPermissionOv { Preconditions.NotEqual(channelId, 0, nameof(channelId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(channelId: channelId); return await SendAsync(HttpMethod.Post, () => $"channel-role/index?channel_id={channelId}", ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -576,7 +585,7 @@ public async Task CreateChanne Preconditions.NotEqual(args.ChannelId, 0, nameof(args.ChannelId)); Preconditions.NotEqual(args.TargetId, 0, nameof(args.TargetId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(channelId: args.ChannelId); return await SendJsonAsync(HttpMethod.Post, () => $"channel-role/create", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -588,7 +597,7 @@ public async Task ModifyChanne if (args.TargetType != PermissionOverwriteTargetType.Role) Preconditions.NotEqual(args.TargetId, 0, nameof(args.TargetId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(channelId: args.ChannelId); return await SendJsonAsync(HttpMethod.Post, () => $"channel-role/update", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -599,7 +608,7 @@ public async Task RemoveChannelPermissionOverwriteAsync(CreateOrRemoveChannelPer Preconditions.NotEqual(args.ChannelId, 0, nameof(args.ChannelId)); Preconditions.NotEqual(args.TargetId, 0, nameof(args.TargetId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(channelId: args.ChannelId); await SendJsonAsync(HttpMethod.Post, () => $"channel-role/delete", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -617,14 +626,16 @@ public async Task> QueryMessagesAsync(ulong channel Preconditions.AtLeast(count, 1, nameof(count)); Preconditions.AtMost(count, 100, nameof(count)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(channelId: channelId); string query = $"?target_id={channelId}"; - if (referenceMessageId is not null) query += $"&msg_id={referenceMessageId}"; - if (queryPin is not null) query += $"&pin={queryPin switch { true => 1, false => 0 }}"; + if (referenceMessageId is not null) + query += $"&msg_id={referenceMessageId}"; + if (queryPin is not null) + query += $"&pin={queryPin switch { true => 1, false => 0 }}"; string flag = dir switch { - Direction.Before => "&flag=before", + Direction.Before => "&flag=before", Direction.Around => "&flag=around", Direction.After => "&flag=after", Direction.Unspecified => "", @@ -640,7 +651,7 @@ public async Task GetMessageAsync(Guid messageId, RequestOptions option { Preconditions.NotEqual(messageId, Guid.Empty, nameof(messageId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); return await SendAsync(HttpMethod.Get, () => $"message/view?msg_id={messageId}", ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -649,11 +660,11 @@ public async Task CreateMessageAsync(CreateMessageParams { Preconditions.NotNull(args, nameof(args)); Preconditions.NotEqual(args.ChannelId, 0, nameof(args.ChannelId)); - + if (args.Content?.Length > KookConfig.MaxMessageSize) throw new ArgumentException(message: $"Message content is too long, length must be less or equal to {KookConfig.MaxMessageSize}.", paramName: nameof(args.Content)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(channelId: args.ChannelId); return await SendJsonAsync(HttpMethod.Post, () => $"message/create", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -663,11 +674,11 @@ public async Task ModifyMessageAsync(ModifyMessageParams args, RequestOptions op Preconditions.NotNull(args, nameof(args)); Preconditions.NotEqual(args.MessageId, Guid.Empty, nameof(args.MessageId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); await SendJsonAsync(HttpMethod.Post, () => $"message/update", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task DeleteMessageAsync(DeleteMessageParams args, RequestOptions options = null) { Preconditions.NotEqual(args.MessageId, Guid.Empty, nameof(args.MessageId)); @@ -681,13 +692,13 @@ public async Task> GetReactionUsersAsy { Preconditions.NotEqual(messageId, Guid.Empty, nameof(messageId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); - return await SendAsync>(HttpMethod.Get, + return await SendAsync>(HttpMethod.Get, #if NET462 () => $"message/reaction-list?msg_id={messageId}&emoji={WebUtility.UrlEncode(emojiId)}", #else - () => $"message/reaction-list?msg_id={messageId}&emoji={HttpUtility.UrlEncode(emojiId)}", + () => $"message/reaction-list?msg_id={messageId}&emoji={HttpUtility.UrlEncode(emojiId)}", #endif ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -696,7 +707,7 @@ public async Task AddReactionAsync(AddReactionParams args, RequestOptions option { Preconditions.NotNull(args, nameof(args)); Preconditions.NotEqual(args.MessageId, Guid.Empty, nameof(args.MessageId)); - + var ids = new BucketIds(); await SendJsonAsync(HttpMethod.Post, () => $"message/add-reaction", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -707,7 +718,7 @@ public async Task RemoveReactionAsync(RemoveReactionParams args, RequestOptions Preconditions.NotEqual(args.MessageId, Guid.Empty, nameof(args.MessageId)); if (args.UserId is not null) Preconditions.NotEqual(args.UserId, 0, nameof(args.MessageId)); - + var ids = new BucketIds(); await SendJsonAsync(HttpMethod.Post, () => $"message/delete-reaction", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -732,24 +743,25 @@ public IAsyncEnumerable> GetAudioChannelsUserConnec } #endregion - + #region User Chats public IAsyncEnumerable> GetUserChatsAsync(int limit = KookConfig.MaxItemsPerBatchByDefault, int fromPage = 1, RequestOptions options = null) { options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); return SendPagedAsync(HttpMethod.Get, (pageSize, page) => $"user-chat/list?page_size={pageSize}&page={page}", - ids, clientBucket: ClientBucketType.SendEdit, pageMeta: new PageMeta(page: fromPage, pageSize: limit), options: options);; + ids, clientBucket: ClientBucketType.SendEdit, pageMeta: new PageMeta(page: fromPage, pageSize: limit), options: options); + ; } public async Task GetUserChatAsync(Guid chatCode, RequestOptions options = null) { Preconditions.NotEqual(chatCode, Guid.Empty, nameof(chatCode)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); return await SendAsync(HttpMethod.Get, () => $"user-chat/view?chat_code={chatCode:N}", ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -758,7 +770,7 @@ public async Task CreateUserChatAsync(CreateUserChatParams args, Reque { Preconditions.NotNull(args, nameof(args)); Preconditions.NotEqual(args.UserId, 0, nameof(args.UserId)); - + var ids = new BucketIds(); return await SendJsonAsync(HttpMethod.Post, () => $"user-chat/create", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -767,7 +779,7 @@ public async Task DeleteUserChatAsync(DeleteUserChatParams args, RequestOptions { Preconditions.NotNull(args, nameof(args)); Preconditions.NotEqual(args.ChatCode, Guid.Empty, nameof(args.ChatCode)); - + var ids = new BucketIds(); await SendJsonAsync(HttpMethod.Post, () => $"user-chat/delete", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -784,28 +796,30 @@ public async Task GetDirectMessageAsync(Guid messageId, Guid? cha var messages = await QueryDirectMessagesAsync(chatCode, userId, messageId, Direction.Around, 50, options); int count = messages.Count; DirectMessage message = messages.SingleOrDefault(x => x.Id == messageId); - if (message is not null) return message; + if (message is not null) + return message; // We have fetched all messages, but the message we're looking for is not there, hence null - if (count < 50) return null; + if (count < 50) + return null; // Try getting by fetching the message next to the targeted one // Try getting by before mode DirectMessage messageBefore = (await QueryDirectMessagesAsync(chatCode, userId, messageId, Direction.Before, 1, options)).SingleOrDefault(x => x.Id == messageId); if (messageBefore is not null) return (await QueryDirectMessagesAsync(chatCode, userId, messageBefore.Id, Direction.After, 1, options)).SingleOrDefault(x => x.Id == messageId); - + // Try getting by after mode DirectMessage messageAfter = (await QueryDirectMessagesAsync(chatCode, userId, messageId, Direction.After, 1, options)).SingleOrDefault(x => x.Id == messageId); if (messageAfter is not null) return (await QueryDirectMessagesAsync(chatCode, userId, messageAfter.Id, Direction.Before, 1, options)).SingleOrDefault(x => x.Id == messageId); - + // Try getting by fetching the message without reference var messagesWithoutReference = await QueryDirectMessagesAsync(chatCode, userId, null, Direction.Unspecified, 50, options); message = messagesWithoutReference.SingleOrDefault(x => x.Id == messageId); return message; } - + public async Task> QueryDirectMessagesAsync(Guid? chatCode = null, ulong? userId = null, Guid? referenceMessageId = null, Direction dir = Direction.Unspecified, int count = 50, RequestOptions options = null) @@ -817,7 +831,7 @@ public async Task> QueryDirectMessagesAsync(G Preconditions.AtLeast(count, 1, nameof(count)); Preconditions.AtMost(count, 100, nameof(count)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); string query = (chatCode is not null, userId is not null) switch { @@ -826,15 +840,17 @@ public async Task> QueryDirectMessagesAsync(G (false, true) => $"?target_id={userId}", _ => string.Empty }; - if (referenceMessageId is not null) query += $"&msg_id={referenceMessageId}"; + if (referenceMessageId is not null) + query += $"&msg_id={referenceMessageId}"; string flag = dir switch { - Direction.Before => "before", + Direction.Before => "before", Direction.Around => "around", Direction.After => "after", _ => string.Empty }; - if (dir != Direction.Unspecified) query += $"&flag={flag}"; + if (dir != Direction.Unspecified) + query += $"&flag={flag}"; query += $"&page_size={count}"; QueryUserChatMessagesResponse queryMessagesResponse = await SendAsync(HttpMethod.Get, () => $"direct-message/list{query}", ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); return queryMessagesResponse.Items; @@ -845,25 +861,25 @@ public async Task CreateDirectMessageAsync(CreateDi Preconditions.NotNull(args, nameof(args)); if (args.ChatCode is null && args.UserId is null) throw new ArgumentException(message: $"At least one argument must be provided between {nameof(args.ChatCode)} and {nameof(args.UserId)}.", paramName: $"{nameof(args.ChatCode)}&{nameof(args.UserId)}"); - + if (args.Content?.Length > KookConfig.MaxMessageSize) throw new ArgumentException(message: $"Message content is too long, length must be less or equal to {KookConfig.MaxMessageSize}.", paramName: nameof(args.Content)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); return await SendJsonAsync(HttpMethod.Post, () => $"direct-message/create", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task ModifyDirectMessageAsync(ModifyDirectMessageParams args, RequestOptions options = null) { Preconditions.NotNull(args, nameof(args)); Preconditions.NotEqual(args.MessageId, Guid.Empty, nameof(args.MessageId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); await SendJsonAsync(HttpMethod.Post, () => $"direct-message/update", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task DeleteDirectMessageAsync(DeleteDirectMessageParams args, RequestOptions options = null) { Preconditions.NotEqual(args.MessageId, Guid.Empty, nameof(args.MessageId)); @@ -872,12 +888,12 @@ public async Task DeleteDirectMessageAsync(DeleteDirectMessageParams args, Reque var ids = new BucketIds(); await SendJsonAsync(HttpMethod.Post, () => $"direct-message/delete", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task> GetDirectMessageReactionUsersAsync(Guid messageId, string emojiId, RequestOptions options = null) { Preconditions.NotEqual(messageId, Guid.Empty, nameof(messageId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); return await SendAsync>(HttpMethod.Get, #if NET462 @@ -892,7 +908,7 @@ public async Task AddDirectMessageReactionAsync(AddReactionParams args, RequestO { Preconditions.NotNull(args, nameof(args)); Preconditions.NotEqual(args.MessageId, Guid.Empty, nameof(args.MessageId)); - + var ids = new BucketIds(); await SendJsonAsync(HttpMethod.Post, () => $"direct-message/add-reaction", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -903,15 +919,15 @@ public async Task RemoveDirectMessageReactionAsync(RemoveReactionParams args, Re Preconditions.NotEqual(args.MessageId, Guid.Empty, nameof(args.MessageId)); if (args.UserId is not null) Preconditions.NotEqual(args.UserId, 0, nameof(args.MessageId)); - + var ids = new BucketIds(); await SendJsonAsync(HttpMethod.Post, () => $"direct-message/delete-reaction", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + #endregion - + #region Gateway - + public async Task GetBotGatewayAsync(bool isCompressed = true, RequestOptions options = null) { options = RequestOptions.CreateOrClone(options); @@ -926,21 +942,21 @@ public async Task GetVoiceGatewayAsync(ulong channelId, } #endregion - + #region Users - + public async Task GetSelfUserAsync(RequestOptions options = null) { options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); return await SendAsync(HttpMethod.Get, () => "user/me", ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task GetUserAsync(ulong userId, RequestOptions options = null) { Preconditions.NotEqual(userId, 0, nameof(userId)); - + var ids = new BucketIds(); return await SendAsync(HttpMethod.Get, () => $"user/view?user_id={userId}", ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -949,11 +965,11 @@ public async Task GetGuildMemberAsync(ulong guildId, ulong userId, { Preconditions.NotEqual(userId, 0, nameof(userId)); Preconditions.NotEqual(guildId, 0, nameof(guildId)); - + var ids = new BucketIds(guildId: guildId); return await SendAsync(HttpMethod.Get, () => $"user/view?user_id={userId}&guild_id={guildId}", ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task GoOfflineAsync(RequestOptions options = null) { var ids = new BucketIds(); @@ -968,7 +984,7 @@ public async Task CreateAssetAsync(CreateAssetParams args, { Preconditions.NotNull(args, nameof(args)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); return await SendMultipartAsync(HttpMethod.Post, () => $"asset/create", args.ToDictionary(), ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -981,13 +997,13 @@ public IAsyncEnumerable> GetGuildRolesAsync(ulong guil { Preconditions.NotEqual(guildId, 0, nameof(guildId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); return SendPagedAsync(HttpMethod.Get, (pageSize, page) => $"guild-role/list?guild={guildId}&page_size={pageSize}&page={page}", ids, clientBucket: ClientBucketType.SendEdit, pageMeta: new PageMeta(page: fromPage, pageSize: limit), options: options); } - + public async Task CreateGuildRoleAsync(CreateGuildRoleParams args, RequestOptions options = null) { Preconditions.NotNull(args, nameof(args)); @@ -997,7 +1013,7 @@ public async Task CreateGuildRoleAsync(CreateGuildRoleParams args, Request var ids = new BucketIds(guildId: args.GuildId); return await SendJsonAsync(HttpMethod.Post, () => $"guild-role/create", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task ModifyGuildRoleAsync(ModifyGuildRoleParams args, RequestOptions options = null) { Preconditions.NotNull(args, nameof(args)); @@ -1027,7 +1043,7 @@ public async Task AddRoleAsync(AddOrRemoveRoleParams ar var ids = new BucketIds(guildId: args.GuildId); return await SendJsonAsync(HttpMethod.Post, () => $"guild-role/grant", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task RemoveRoleAsync(AddOrRemoveRoleParams args, RequestOptions options = null) { Preconditions.NotNull(args, nameof(args)); @@ -1057,7 +1073,7 @@ public async Task UpdateIntimacyValueAsync(UpdateIntimacyValueParams args, Reque Preconditions.NotEqual(args.UserId, 0, nameof(args.UserId)); Preconditions.AtLeast(args.Score, KookConfig.MinIntimacyScore, nameof(args.Score)); Preconditions.AtMost(args.Score, KookConfig.MaxIntimacyScore, nameof(args.Score)); - + options = RequestOptions.CreateOrClone(options); var ids = new BucketIds(); @@ -1072,13 +1088,13 @@ public IAsyncEnumerable> GetGuildEmotesAsync(ulong gu { Preconditions.NotEqual(guildId, 0, nameof(guildId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(guildId: guildId); return SendPagedAsync(HttpMethod.Get, (pageSize, page) => $"guild-emoji/list?guild_id={guildId}&page_size={pageSize}&page={page}", ids, clientBucket: ClientBucketType.SendEdit, pageMeta: new PageMeta(page: fromPage, pageSize: limit), options: options); } - + public async Task CreateGuildEmoteAsync(CreateGuildEmoteParams args, RequestOptions options = null) { Preconditions.NotNull(args, nameof(args)); @@ -1088,7 +1104,7 @@ public async Task CreateGuildEmoteAsync(CreateGuildEmoteParams args, Requ Preconditions.AtMost(args.Name.Length, 32, nameof(args.Name.Length)); } options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(guildId: args.GuildId); return await SendMultipartAsync(HttpMethod.Post, () => $"guild-emoji/create", args.ToDictionary(), ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -1102,20 +1118,20 @@ public async Task ModifyGuildEmoteAsync(ModifyGuildEmoteParams args, RequestOpti Preconditions.AtMost(args.Name.Length, 32, nameof(args.Name.Length)); } options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); await SendJsonAsync(HttpMethod.Post, () => $"guild-emoji/update", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task DeleteGuildEmoteAsync(DeleteGuildEmoteParams args, RequestOptions options = null) { Preconditions.NotNull(args, nameof(args)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(); await SendJsonAsync(HttpMethod.Post, () => $"guild-emoji/delete", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + #endregion #region Guild Invites @@ -1153,7 +1169,7 @@ public async Task CreateGuildInviteAsync(CreateGuildI if (args.ChannelId is not null) Preconditions.NotEqual(args.ChannelId, 0, nameof(args.ChannelId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(guildId: args.GuildId ?? 0, channelId: args.ChannelId ?? 0); return await SendJsonAsync(HttpMethod.Post, () => $"invite/create", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -1167,7 +1183,7 @@ public async Task DeleteGuildInviteAsync(DeleteGuildInviteParams args, RequestOp if (args.ChannelId is not null) Preconditions.NotEqual(args.ChannelId, 0, nameof(args.ChannelId)); options = RequestOptions.CreateOrClone(options); - + var ids = new BucketIds(guildId: args.GuildId ?? 0, channelId: args.ChannelId ?? 0); await SendJsonAsync(HttpMethod.Post, () => $"invite/delete", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } @@ -1184,7 +1200,7 @@ public async Task> GetGuildBansAsync(ulong guildId, Req var ids = new BucketIds(guildId: guildId); return await SendAsync>(HttpMethod.Get, () => $"blacklist/list?guild_id={guildId}", ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task CreateGuildBanAsync(CreateGuildBanParams args, RequestOptions options = null) { Preconditions.NotNull(args, nameof(args)); @@ -1200,7 +1216,7 @@ public async Task CreateGuildBanAsync(CreateGuildBanParams args, RequestOptions var ids = new BucketIds(guildId: args.GuildId); await SendJsonAsync(HttpMethod.Post, () => $"blacklist/create", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task RemoveGuildBanAsync(RemoveGuildBanParams args, RequestOptions options = null) { Preconditions.NotNull(args, nameof(args)); @@ -1211,7 +1227,7 @@ public async Task RemoveGuildBanAsync(RemoveGuildBanParams args, RequestOptions var ids = new BucketIds(guildId: args.GuildId); await SendJsonAsync(HttpMethod.Post, () => $"blacklist/delete", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + #endregion @@ -1239,7 +1255,7 @@ public IAsyncEnumerable> GetGamesAsync(int limit = Koo (pageSize, page) => $"game?page_size={pageSize}&page={page}", ids, clientBucket: ClientBucketType.SendEdit, pageMeta: new PageMeta(page: fromPage, pageSize: limit), options: options); } - + public async Task CreateGameAsync(CreateGameParams args, RequestOptions options = null) { Preconditions.NotNull(args, nameof(args)); @@ -1249,7 +1265,7 @@ public async Task CreateGameAsync(CreateGameParams args, RequestOptions op var ids = new BucketIds(); return await SendJsonAsync(HttpMethod.Post, () => $"game/create", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task ModifyGameAsync(ModifyGameParams args, RequestOptions options = null) { Preconditions.NotNull(args, nameof(args)); @@ -1259,7 +1275,7 @@ public async Task ModifyGameAsync(ModifyGameParams args, RequestOptions op var ids = new BucketIds(); return await SendJsonAsync(HttpMethod.Post, () => $"game/update", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task DeleteGameAsync(DeleteGameParams args, RequestOptions options = null) { Preconditions.NotNull(args, nameof(args)); @@ -1269,7 +1285,7 @@ public async Task DeleteGameAsync(DeleteGameParams args, RequestOptions options var ids = new BucketIds(); await SendJsonAsync(HttpMethod.Post, () => $"game/delete", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task BeginActivityAsync(BeginActivityParams args, RequestOptions options = null) { Preconditions.NotNull(args, nameof(args)); @@ -1290,7 +1306,7 @@ public async Task BeginActivityAsync(BeginActivityParams args, RequestOptions op var ids = new BucketIds(); await SendJsonAsync(HttpMethod.Post, () => $"game/activity", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false); } - + public async Task EndActivityAsync(EndGameActivityParams args, RequestOptions options = null) { Preconditions.NotNull(args, nameof(args)); @@ -1301,7 +1317,7 @@ public async Task EndActivityAsync(EndGameActivityParams args, RequestOptions op } #endregion - + #region Helpers protected void CheckState() @@ -1312,11 +1328,11 @@ protected void CheckState() protected static double ToMilliseconds(Stopwatch stopwatch) => Math.Round((double)stopwatch.ElapsedTicks / (double)Stopwatch.Frequency * 1000.0, 2); protected string SerializeJson(object payload) { - return payload is null - ? string.Empty + return payload is null + ? string.Empty : JsonSerializer.Serialize(payload, _serializerOptions); } - + protected async Task DeserializeJsonAsync(Stream jsonStream) { try @@ -1371,7 +1387,7 @@ internal Dictionary ToMajorParametersDictionary() }; } } - + private static string GetEndpoint(Expression> endpointExpr) { return endpointExpr.Compile()(); @@ -1474,4 +1490,4 @@ private static string GetFieldName(Expression expr) } #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/KookRestClient.cs b/src/Kook.Net.Rest/KookRestClient.cs index 4612d334..2fe6070f 100644 --- a/src/Kook.Net.Rest/KookRestClient.cs +++ b/src/Kook.Net.Rest/KookRestClient.cs @@ -14,18 +14,18 @@ public class KookRestClient : BaseKookClient, IKookClient Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, NumberHandling = JsonNumberHandling.AllowReadingFromString }; - + /// /// Gets the logged-in user. /// public new RestSelfUser CurrentUser { get => base.CurrentUser as RestSelfUser; internal set => base.CurrentUser = value; } public KookRestClient() : this(new KookRestConfig()) { } - + public KookRestClient(KookRestConfig config) : base(config, CreateApiClient(config)) { } - + internal KookRestClient(KookRestConfig config, API.KookRestApiClient api) : base(config, api) { } - + private static API.KookRestApiClient CreateApiClient(KookRestConfig config) => new API.KookRestApiClient(config.RestClientProvider, KookRestConfig.UserAgent, acceptLanguage: config.AcceptLanguage, defaultRetryMode: config.DefaultRetryMode, serializerOptions: SerializerOptions); @@ -37,7 +37,7 @@ internal override void Dispose(bool disposing) base.Dispose(disposing); } - + /// internal override async Task OnLoginAsync(TokenType tokenType, string token) { @@ -65,7 +65,7 @@ public Task GetGuildAsync(ulong id, RequestOptions options = null) /// public Task> GetGuildsAsync(RequestOptions options = null) => ClientHelper.GetGuildsAsync(this, options); - + #endregion #region Channels @@ -76,7 +76,7 @@ public Task GetDMChannelAsync(Guid chatCode, RequestOptions optio => ClientHelper.GetDMChannelAsync(this, chatCode, options); public Task> GetDMChannelsAsync(RequestOptions options = null) => ClientHelper.GetDMChannelsAsync(this, options); - + #endregion #region Roles @@ -87,7 +87,7 @@ public Task RemoveRoleAsync(ulong guildId, ulong userId, uint roleId) => ClientHelper.RemoveRoleAsync(this, guildId, userId, roleId); #endregion - + #region Users public Task GetUserAsync(ulong id, RequestOptions options = null) @@ -110,9 +110,9 @@ public Task RemoveDirectMessageReactionAsync(Guid messageId, ulong userId, IEmot => MessageHelper.RemoveDirectMessageReactionAsync(messageId, userId, emote, this, options); #endregion - + #region Assets - + public Task CreateAssetAsync(string path, string fileName, RequestOptions options = null) => ClientHelper.CreateAssetAsync(this, File.OpenRead(path), fileName, options); public Task CreateAssetAsync(Stream stream, string fileName, RequestOptions options = null) @@ -121,7 +121,7 @@ public Task CreateAssetAsync(Stream stream, string fileName, RequestOpti #endregion #region Games - + public IAsyncEnumerable> GetGamesAsync(RequestOptions options = null) => ClientHelper.GetGamesAsync(this, options); public Task CreateGameAsync(string name, string processName, string iconUrl, RequestOptions options = null) @@ -147,7 +147,7 @@ async Task> IKookClient.GetGuildsAsync(CacheMode mod else return ImmutableArray.Create(); } - + /// async Task IKookClient.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) { @@ -156,7 +156,7 @@ async Task IKookClient.GetUserAsync(ulong id, CacheMode mode, RequestOpti else return null; } - + /// async Task IKookClient.GetChannelAsync(ulong id, CacheMode mode, RequestOptions options) { @@ -183,4 +183,4 @@ async Task> IKookClient.GetDMChannelsAsync(Cache } #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/KookRestConfig.cs b/src/Kook.Net.Rest/KookRestConfig.cs index 53d0200a..250d473c 100644 --- a/src/Kook.Net.Rest/KookRestConfig.cs +++ b/src/Kook.Net.Rest/KookRestConfig.cs @@ -8,4 +8,4 @@ namespace Kook.Rest; public class KookRestConfig : KookConfig { public RestClientProvider RestClientProvider { get; set; } = DefaultRestClientProvider.Instance; -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/ButtonClickEventTypeConverter.cs b/src/Kook.Net.Rest/Net/Converters/Cards/ButtonClickEventTypeConverter.cs index 894aec27..b3a13842 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/ButtonClickEventTypeConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/ButtonClickEventTypeConverter.cs @@ -27,4 +27,4 @@ public override void Write(Utf8JsonWriter writer, ButtonClickEventType value, Js _ => throw new ArgumentOutOfRangeException(nameof(value), value, null) }); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/ButtonThemeConverter.cs b/src/Kook.Net.Rest/Net/Converters/Cards/ButtonThemeConverter.cs index 3a9c4173..066fff70 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/ButtonThemeConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/ButtonThemeConverter.cs @@ -33,4 +33,4 @@ public override void Write(Utf8JsonWriter writer, ButtonTheme value, JsonSeriali _ => throw new ArgumentOutOfRangeException(nameof(value), value, null) }); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/CardConverter.cs b/src/Kook.Net.Rest/Net/Converters/Cards/CardConverter.cs index a3e40f80..fb3890cf 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/CardConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/CardConverter.cs @@ -1,7 +1,7 @@ +using Kook.API; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; -using Kook.API; namespace Kook.Net.Converters; @@ -20,7 +20,7 @@ public override CardBase Read(ref Utf8JsonReader reader, Type typeToConvert, Jso } public override void Write(Utf8JsonWriter writer, CardBase value, JsonSerializerOptions options) - { + { switch (value.Type) { case CardType.Card: @@ -30,4 +30,4 @@ public override void Write(Utf8JsonWriter writer, CardBase value, JsonSerializer throw new ArgumentOutOfRangeException(nameof(CardType)); } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/CardSizeConverter.cs b/src/Kook.Net.Rest/Net/Converters/Cards/CardSizeConverter.cs index 010e2aff..d5516edb 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/CardSizeConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/CardSizeConverter.cs @@ -25,4 +25,4 @@ public override void Write(Utf8JsonWriter writer, CardSize value, JsonSerializer _ => throw new ArgumentOutOfRangeException(nameof(value), value, null) }); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/CardThemeConverter.cs b/src/Kook.Net.Rest/Net/Converters/Cards/CardThemeConverter.cs index 9c41018c..53611a91 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/CardThemeConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/CardThemeConverter.cs @@ -35,4 +35,4 @@ public override void Write(Utf8JsonWriter writer, CardTheme value, JsonSerialize _ => throw new ArgumentOutOfRangeException(nameof(value), value, null) }); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/CardTypeConverter.cs b/src/Kook.Net.Rest/Net/Converters/Cards/CardTypeConverter.cs index 50931763..9f20c197 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/CardTypeConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/CardTypeConverter.cs @@ -23,4 +23,4 @@ public override void Write(Utf8JsonWriter writer, CardType value, JsonSerializer _ => throw new ArgumentOutOfRangeException(nameof(value), value, null) }); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/ColorConverter.cs b/src/Kook.Net.Rest/Net/Converters/Cards/ColorConverter.cs index 7bf9f2e0..f2152f1f 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/ColorConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/ColorConverter.cs @@ -17,4 +17,4 @@ public override void Write(Utf8JsonWriter writer, Color? value, JsonSerializerOp { writer.WriteStringValue(value.HasValue ? $"#{value.Value.RawValue:X6}" : string.Empty); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/CountdownModeConverter.cs b/src/Kook.Net.Rest/Net/Converters/Cards/CountdownModeConverter.cs index 57b9e94b..e33a7f20 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/CountdownModeConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/CountdownModeConverter.cs @@ -27,4 +27,4 @@ public override void Write(Utf8JsonWriter writer, CountdownMode value, JsonSeria _ => throw new ArgumentOutOfRangeException(nameof(value), value, null) }); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/ElementConverter.cs b/src/Kook.Net.Rest/Net/Converters/Cards/ElementConverter.cs index ed57cd2b..7fcb46d7 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/ElementConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/ElementConverter.cs @@ -1,7 +1,7 @@ +using Kook.API; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; -using Kook.API; namespace Kook.Net.Converters; @@ -45,4 +45,4 @@ public override void Write(Utf8JsonWriter writer, ElementBase value, JsonSeriali throw new ArgumentOutOfRangeException(nameof(ElementType)); } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/ElementTypeConverter.cs b/src/Kook.Net.Rest/Net/Converters/Cards/ElementTypeConverter.cs index 926157ec..233ab9b1 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/ElementTypeConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/ElementTypeConverter.cs @@ -31,4 +31,4 @@ public override void Write(Utf8JsonWriter writer, ElementType value, JsonSeriali _ => throw new ArgumentOutOfRangeException(nameof(value), value, null) }); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/ImageSizeConverter.cs b/src/Kook.Net.Rest/Net/Converters/Cards/ImageSizeConverter.cs index d937ebaa..001c95f6 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/ImageSizeConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/ImageSizeConverter.cs @@ -25,4 +25,4 @@ public override void Write(Utf8JsonWriter writer, ImageSize value, JsonSerialize _ => throw new ArgumentOutOfRangeException(nameof(value), value, null) }); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/ModuleConverter.cs b/src/Kook.Net.Rest/Net/Converters/Cards/ModuleConverter.cs index d962238c..b686f824 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/ModuleConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/ModuleConverter.cs @@ -1,7 +1,7 @@ +using Kook.API; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; -using Kook.API; namespace Kook.Net.Converters; @@ -31,7 +31,7 @@ public override ModuleBase Read(ref Utf8JsonReader reader, Type typeToConvert, J public override void Write(Utf8JsonWriter writer, ModuleBase value, JsonSerializerOptions options) { - + switch (value.Type) { case ModuleType.Header: @@ -74,4 +74,4 @@ public override void Write(Utf8JsonWriter writer, ModuleBase value, JsonSerializ throw new ArgumentOutOfRangeException(nameof(ModuleType)); } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/ModuleTypeConverter.cs b/src/Kook.Net.Rest/Net/Converters/Cards/ModuleTypeConverter.cs index c83d5120..0d909f7b 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/ModuleTypeConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/ModuleTypeConverter.cs @@ -45,4 +45,4 @@ public override void Write(Utf8JsonWriter writer, ModuleType value, JsonSerializ _ => throw new ArgumentOutOfRangeException(nameof(value), value, null) }); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/NullableColorConverter.cs b/src/Kook.Net.Rest/Net/Converters/Cards/NullableColorConverter.cs index 30657417..568f88bc 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/NullableColorConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/NullableColorConverter.cs @@ -17,4 +17,4 @@ public override void Write(Utf8JsonWriter writer, Color value, JsonSerializerOpt { writer.WriteStringValue($"#{value.RawValue:X6}"); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Cards/SectionAccessoryModeConvertercs.cs b/src/Kook.Net.Rest/Net/Converters/Cards/SectionAccessoryModeConvertercs.cs index ab742049..0d068663 100644 --- a/src/Kook.Net.Rest/Net/Converters/Cards/SectionAccessoryModeConvertercs.cs +++ b/src/Kook.Net.Rest/Net/Converters/Cards/SectionAccessoryModeConvertercs.cs @@ -26,4 +26,4 @@ public override void Write(Utf8JsonWriter writer, SectionAccessoryMode value, Js _ => throw new ArgumentOutOfRangeException(nameof(value), value, null) }); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/ChatCodeConverter.cs b/src/Kook.Net.Rest/Net/Converters/ChatCodeConverter.cs index f687f5a7..6e6e1b98 100644 --- a/src/Kook.Net.Rest/Net/Converters/ChatCodeConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/ChatCodeConverter.cs @@ -14,4 +14,4 @@ public override void Write(Utf8JsonWriter writer, Guid value, JsonSerializerOpti { writer.WriteStringValue(value.ToString("N")); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/DateTimeOffsetUnixTimeMillisecondsConverter.cs b/src/Kook.Net.Rest/Net/Converters/DateTimeOffsetUnixTimeMillisecondsConverter.cs index 5f36d2e6..465474f7 100644 --- a/src/Kook.Net.Rest/Net/Converters/DateTimeOffsetUnixTimeMillisecondsConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/DateTimeOffsetUnixTimeMillisecondsConverter.cs @@ -21,4 +21,4 @@ public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSeri else writer.WriteNumberValue(value.ToUnixTimeMilliseconds()); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/DateTimeOffsetUnixTimeSecondsConverter.cs b/src/Kook.Net.Rest/Net/Converters/DateTimeOffsetUnixTimeSecondsConverter.cs index dc7d4ee5..ca3b0515 100644 --- a/src/Kook.Net.Rest/Net/Converters/DateTimeOffsetUnixTimeSecondsConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/DateTimeOffsetUnixTimeSecondsConverter.cs @@ -21,4 +21,4 @@ public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSeri else writer.WriteNumberValue(value.ToUnixTimeSeconds()); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Embeds/EmbedConverter.cs b/src/Kook.Net.Rest/Net/Converters/Embeds/EmbedConverter.cs index 35439424..f281f197 100644 --- a/src/Kook.Net.Rest/Net/Converters/Embeds/EmbedConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Embeds/EmbedConverter.cs @@ -1,7 +1,7 @@ +using Kook.API; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; -using Kook.API; namespace Kook.Net.Converters; @@ -38,4 +38,4 @@ public override void Write(Utf8JsonWriter writer, EmbedBase value, JsonSerialize break; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Embeds/EmbedTypeConverter.cs b/src/Kook.Net.Rest/Net/Converters/Embeds/EmbedTypeConverter.cs index b6d405f0..861ab26c 100644 --- a/src/Kook.Net.Rest/Net/Converters/Embeds/EmbedTypeConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Embeds/EmbedTypeConverter.cs @@ -27,4 +27,4 @@ public override void Write(Utf8JsonWriter writer, EmbedType value, JsonSerialize _ => throw new ArgumentOutOfRangeException(nameof(value), value, null) }); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/MusicProviderConverter.cs b/src/Kook.Net.Rest/Net/Converters/MusicProviderConverter.cs index 808bdcd8..292b65ad 100644 --- a/src/Kook.Net.Rest/Net/Converters/MusicProviderConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/MusicProviderConverter.cs @@ -27,4 +27,4 @@ public override void Write(Utf8JsonWriter writer, MusicProvider value, JsonSeria _ => string.Empty }); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/NullableChatCodeConverter.cs b/src/Kook.Net.Rest/Net/Converters/NullableChatCodeConverter.cs index 9daeb3c3..085c9491 100644 --- a/src/Kook.Net.Rest/Net/Converters/NullableChatCodeConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/NullableChatCodeConverter.cs @@ -14,8 +14,11 @@ internal class NullableChatCodeConverter : JsonConverter public override void Write(Utf8JsonWriter writer, Guid? value, JsonSerializerOptions options) { - if (value is null) writer.WriteNullValue(); - else if (value == Guid.Empty) writer.WriteStringValue(string.Empty); - else writer.WriteStringValue(value.Value.ToString("N")); + if (value is null) + writer.WriteNullValue(); + else if (value == Guid.Empty) + writer.WriteStringValue(string.Empty); + else + writer.WriteStringValue(value.Value.ToString("N")); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/NullableDateTimeOffsetConverter.cs b/src/Kook.Net.Rest/Net/Converters/NullableDateTimeOffsetConverter.cs index 21224c15..addca040 100644 --- a/src/Kook.Net.Rest/Net/Converters/NullableDateTimeOffsetConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/NullableDateTimeOffsetConverter.cs @@ -8,13 +8,16 @@ internal class NullableDateTimeOffsetConverter : JsonConverter public override DateTimeOffset? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { long tick = reader.GetInt64(); - if (tick == 0) return null; + if (tick == 0) + return null; return DateTimeOffset.FromUnixTimeMilliseconds(tick); } public override void Write(Utf8JsonWriter writer, DateTimeOffset? value, JsonSerializerOptions options) { - if (value is null) writer.WriteNumberValue(0); - else writer.WriteNumberValue(value.Value.ToUnixTimeMilliseconds()); + if (value is null) + writer.WriteNumberValue(0); + else + writer.WriteNumberValue(value.Value.ToUnixTimeMilliseconds()); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/NullableGuidConverter.cs b/src/Kook.Net.Rest/Net/Converters/NullableGuidConverter.cs index 6f4417bd..87e21183 100644 --- a/src/Kook.Net.Rest/Net/Converters/NullableGuidConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/NullableGuidConverter.cs @@ -14,8 +14,11 @@ internal class NullableGuidConverter : JsonConverter public override void Write(Utf8JsonWriter writer, Guid? value, JsonSerializerOptions options) { - if (value is null) writer.WriteNullValue(); - else if (value == Guid.Empty) writer.WriteStringValue(string.Empty); - else writer.WriteStringValue(value.ToString()); + if (value is null) + writer.WriteNullValue(); + else if (value == Guid.Empty) + writer.WriteStringValue(string.Empty); + else + writer.WriteStringValue(value.ToString()); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/NullableNumberBooleanConverter.cs b/src/Kook.Net.Rest/Net/Converters/NullableNumberBooleanConverter.cs index 4bdc01d3..36d8f594 100644 --- a/src/Kook.Net.Rest/Net/Converters/NullableNumberBooleanConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/NullableNumberBooleanConverter.cs @@ -29,4 +29,4 @@ public override void Write(Utf8JsonWriter writer, bool? value, JsonSerializerOpt else writer.WriteNullValue(); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/NullableTimeSpanConverter.cs b/src/Kook.Net.Rest/Net/Converters/NullableTimeSpanConverter.cs index 48e8ee30..c3339278 100644 --- a/src/Kook.Net.Rest/Net/Converters/NullableTimeSpanConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/NullableTimeSpanConverter.cs @@ -8,13 +8,16 @@ internal class NullableTimeSpanConverter : JsonConverter public override TimeSpan? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { ulong tick = reader.GetUInt64(); - if (tick == 0) return null; + if (tick == 0) + return null; return TimeSpan.FromSeconds(tick); } public override void Write(Utf8JsonWriter writer, TimeSpan? value, JsonSerializerOptions options) { - if (value is null) writer.WriteNumberValue(0); - else writer.WriteNumberValue(value.Value.TotalSeconds); + if (value is null) + writer.WriteNumberValue(0); + else + writer.WriteNumberValue(value.Value.TotalSeconds); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/NullableUInt32Converter.cs b/src/Kook.Net.Rest/Net/Converters/NullableUInt32Converter.cs index ef7df4c0..0a969db9 100644 --- a/src/Kook.Net.Rest/Net/Converters/NullableUInt32Converter.cs +++ b/src/Kook.Net.Rest/Net/Converters/NullableUInt32Converter.cs @@ -11,7 +11,7 @@ internal class NullableUInt32Converter : JsonConverter { case JsonTokenType.String: string value = reader.GetString(); - return !string.IsNullOrWhiteSpace(value) && uint.TryParse(value, out uint result) + return !string.IsNullOrWhiteSpace(value) && uint.TryParse(value, out uint result) ? result : null; case JsonTokenType.Number: @@ -23,7 +23,9 @@ internal class NullableUInt32Converter : JsonConverter public override void Write(Utf8JsonWriter writer, uint? value, JsonSerializerOptions options) { - if (value is null) writer.WriteNullValue(); - else writer.WriteStringValue(value.ToString()); + if (value is null) + writer.WriteNullValue(); + else + writer.WriteStringValue(value.ToString()); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/NullableUInt64Converter.cs b/src/Kook.Net.Rest/Net/Converters/NullableUInt64Converter.cs index 9d6408ed..d0d24ffb 100644 --- a/src/Kook.Net.Rest/Net/Converters/NullableUInt64Converter.cs +++ b/src/Kook.Net.Rest/Net/Converters/NullableUInt64Converter.cs @@ -8,14 +8,16 @@ internal class NullableUInt64Converter : JsonConverter public override ulong? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { string value = reader.GetString(); - return !string.IsNullOrWhiteSpace(value) && ulong.TryParse(value, out ulong result) - ? result + return !string.IsNullOrWhiteSpace(value) && ulong.TryParse(value, out ulong result) + ? result : null; } public override void Write(Utf8JsonWriter writer, ulong? value, JsonSerializerOptions options) { - if (value is null) writer.WriteNullValue(); - else writer.WriteStringValue(value.ToString()); + if (value is null) + writer.WriteNullValue(); + else + writer.WriteStringValue(value.ToString()); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/NullableVoiceQualityConverter.cs b/src/Kook.Net.Rest/Net/Converters/NullableVoiceQualityConverter.cs index 8f7e8af6..e2c2f1e9 100644 --- a/src/Kook.Net.Rest/Net/Converters/NullableVoiceQualityConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/NullableVoiceQualityConverter.cs @@ -12,11 +12,11 @@ internal class NullableVoiceQualityConverter : JsonConverter case JsonTokenType.String: string str = reader.GetString(); return int.TryParse(str, out int result) - ? (VoiceQuality?) result + ? (VoiceQuality?)result : null; case JsonTokenType.Number: return reader.TryGetInt32(out int value) - ? (VoiceQuality?) value + ? (VoiceQuality?)value : null; case JsonTokenType.Null: return null; @@ -27,7 +27,9 @@ internal class NullableVoiceQualityConverter : JsonConverter public override void Write(Utf8JsonWriter writer, VoiceQuality? value, JsonSerializerOptions options) { - if (value is null) writer.WriteNullValue(); - else writer.WriteNumberValue((int) value); + if (value is null) + writer.WriteNullValue(); + else + writer.WriteNumberValue((int)value); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/NumberBooleanConverter.cs b/src/Kook.Net.Rest/Net/Converters/NumberBooleanConverter.cs index 5e83143c..9f5d528b 100644 --- a/src/Kook.Net.Rest/Net/Converters/NumberBooleanConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/NumberBooleanConverter.cs @@ -24,4 +24,4 @@ public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOpti { writer.WriteBooleanValue(value); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/PageSortInfoConverter.cs b/src/Kook.Net.Rest/Net/Converters/PageSortInfoConverter.cs index 1a0491e2..c084065a 100644 --- a/src/Kook.Net.Rest/Net/Converters/PageSortInfoConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/PageSortInfoConverter.cs @@ -1,6 +1,6 @@ +using Kook.API.Rest; using System.Text.Json; using System.Text.Json.Serialization; -using Kook.API.Rest; namespace Kook.Net.Converters; @@ -8,7 +8,7 @@ internal class PageSortInfoConverter : JsonConverter { public override PageSortInfo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - PageSortInfo pageSortInfo = new() {SortKey = null, SortMode = API.Rest.SortMode.Unspecified}; + PageSortInfo pageSortInfo = new() { SortKey = null, SortMode = API.Rest.SortMode.Unspecified }; while (reader.Read()) { switch (reader.TokenType) @@ -45,4 +45,4 @@ public override void Write(Utf8JsonWriter writer, PageSortInfo value, JsonSerial } writer.WriteEndObject(); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/PermissionOverwriteTargetTypeConverter.cs b/src/Kook.Net.Rest/Net/Converters/PermissionOverwriteTargetTypeConverter.cs index 5590b7ec..dcb09be0 100644 --- a/src/Kook.Net.Rest/Net/Converters/PermissionOverwriteTargetTypeConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/PermissionOverwriteTargetTypeConverter.cs @@ -1,6 +1,6 @@ +using Kook.API.Rest; using System.Text.Json; using System.Text.Json.Serialization; -using Kook.API.Rest; namespace Kook.Net.Converters; @@ -25,4 +25,4 @@ public override void Write(Utf8JsonWriter writer, PermissionOverwriteTargetType _ => "user_id" }); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Pokes/PokeResourceConverter.cs b/src/Kook.Net.Rest/Net/Converters/Pokes/PokeResourceConverter.cs index 6ab6ba76..83481bbb 100644 --- a/src/Kook.Net.Rest/Net/Converters/Pokes/PokeResourceConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Pokes/PokeResourceConverter.cs @@ -1,7 +1,7 @@ +using Kook.API; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; -using Kook.API; namespace Kook.Net.Converters; @@ -30,4 +30,4 @@ public override void Write(Utf8JsonWriter writer, PokeResourceBase value, JsonSe break; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Converters/Pokes/PokeResourceTypeConverter.cs b/src/Kook.Net.Rest/Net/Converters/Pokes/PokeResourceTypeConverter.cs index 70aca726..1dc749ab 100644 --- a/src/Kook.Net.Rest/Net/Converters/Pokes/PokeResourceTypeConverter.cs +++ b/src/Kook.Net.Rest/Net/Converters/Pokes/PokeResourceTypeConverter.cs @@ -23,4 +23,4 @@ public override void Write(Utf8JsonWriter writer, PokeResourceType value, JsonSe _ => throw new ArgumentOutOfRangeException(nameof(value), value, null) }); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/DefaultRestClient.cs b/src/Kook.Net.Rest/Net/DefaultRestClient.cs index 9f92e09c..1db68400 100644 --- a/src/Kook.Net.Rest/Net/DefaultRestClient.cs +++ b/src/Kook.Net.Rest/Net/DefaultRestClient.cs @@ -89,7 +89,8 @@ public async Task SendAsync(HttpMethod method, string endpoint, Ca string uri = Path.Combine(_baseUrl, endpoint); using (var restRequest = new HttpRequestMessage(method, uri)) { - if (reason != null) restRequest.Headers.Add("X-Audit-Log-Reason", Uri.EscapeDataString(reason)); + if (reason != null) + restRequest.Headers.Add("X-Audit-Log-Reason", Uri.EscapeDataString(reason)); if (requestHeaders != null) foreach (KeyValuePair> header in requestHeaders) restRequest.Headers.Add(header.Key, header.Value); @@ -102,7 +103,8 @@ public async Task SendAsync(HttpMethod method, string endpoint, st string uri = Path.Combine(_baseUrl, endpoint); using (var restRequest = new HttpRequestMessage(method, uri)) { - if (reason != null) restRequest.Headers.Add("X-Audit-Log-Reason", Uri.EscapeDataString(reason)); + if (reason != null) + restRequest.Headers.Add("X-Audit-Log-Reason", Uri.EscapeDataString(reason)); if (requestHeaders != null) foreach (KeyValuePair> header in requestHeaders) restRequest.Headers.Add(header.Key, header.Value); @@ -118,7 +120,8 @@ public async Task SendAsync(HttpMethod method, string endpoint, IR string uri = Path.Combine(_baseUrl, endpoint); using (var restRequest = new HttpRequestMessage(method, uri)) { - if (reason != null) restRequest.Headers.Add("X-Audit-Log-Reason", Uri.EscapeDataString(reason)); + if (reason != null) + restRequest.Headers.Add("X-Audit-Log-Reason", Uri.EscapeDataString(reason)); if (requestHeaders != null) foreach (KeyValuePair> header in requestHeaders) restRequest.Headers.Add(header.Key, header.Value); @@ -131,33 +134,36 @@ public async Task SendAsync(HttpMethod method, string endpoint, IR switch (p.Value) { #pragma warning disable IDISP004 - case string stringValue: { content.Add(new StringContent(stringValue, Encoding.UTF8, "text/plain"), p.Key); continue; } - case byte[] byteArrayValue: { content.Add(new ByteArrayContent(byteArrayValue), p.Key); continue; } - case Stream streamValue: { content.Add(new StreamContent(streamValue), p.Key); continue; } + case string stringValue: + { content.Add(new StringContent(stringValue, Encoding.UTF8, "text/plain"), p.Key); continue; } + case byte[] byteArrayValue: + { content.Add(new ByteArrayContent(byteArrayValue), p.Key); continue; } + case Stream streamValue: + { content.Add(new StreamContent(streamValue), p.Key); continue; } case MultipartFile fileValue: - { - var stream = fileValue.Stream; - if (!stream.CanSeek) { - memoryStream = new MemoryStream(); - await stream.CopyToAsync(memoryStream).ConfigureAwait(false); - memoryStream.Position = 0; + var stream = fileValue.Stream; + if (!stream.CanSeek) + { + memoryStream = new MemoryStream(); + await stream.CopyToAsync(memoryStream).ConfigureAwait(false); + memoryStream.Position = 0; #pragma warning disable IDISP001 - stream = memoryStream; + stream = memoryStream; #pragma warning restore IDISP001 - } + } - var streamContent = new StreamContent(stream); - var extension = fileValue.Filename.Split('.').Last(); + var streamContent = new StreamContent(stream); + var extension = fileValue.Filename.Split('.').Last(); - if(fileValue.ContentType != null) - streamContent.Headers.ContentType = new MediaTypeHeaderValue(fileValue.ContentType); + if (fileValue.ContentType != null) + streamContent.Headers.ContentType = new MediaTypeHeaderValue(fileValue.ContentType); - content.Add(streamContent, p.Key, fileValue.Filename); + content.Add(streamContent, p.Key, fileValue.Filename); #pragma warning restore IDISP004 - - continue; - } + + continue; + } default: throw new InvalidOperationException($"Unsupported param type \"{p.Value.GetType().Name}\"."); } @@ -213,4 +219,4 @@ private async Task SendInternalAsync(HttpRequestMessage request, C // _ => throw new ArgumentOutOfRangeException(nameof(method), $"Unknown HttpMethod: {method}"), // }; // } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/DefaultRestClientProvider.cs b/src/Kook.Net.Rest/Net/DefaultRestClientProvider.cs index 6db77a8a..ef263ebe 100644 --- a/src/Kook.Net.Rest/Net/DefaultRestClientProvider.cs +++ b/src/Kook.Net.Rest/Net/DefaultRestClientProvider.cs @@ -21,4 +21,4 @@ public static RestClientProvider Create(bool useProxy = false) } }; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Queue/ClientBucket.cs b/src/Kook.Net.Rest/Net/Queue/ClientBucket.cs index b04af1aa..b039b86c 100644 --- a/src/Kook.Net.Rest/Net/Queue/ClientBucket.cs +++ b/src/Kook.Net.Rest/Net/Queue/ClientBucket.cs @@ -33,7 +33,7 @@ static ClientBucket() public static ClientBucket Get(ClientBucketType type) => DefsByType[type]; public static ClientBucket Get(BucketId id) => DefsById[id]; - + public ClientBucketType Type { get; } public BucketId Id { get; } public int WindowCount { get; } @@ -46,4 +46,4 @@ public ClientBucket(ClientBucketType type, BucketId id, int count, int seconds) WindowCount = count; WindowSeconds = seconds; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Queue/GatewayBucket.cs b/src/Kook.Net.Rest/Net/Queue/GatewayBucket.cs index 2e39fab1..734f07db 100644 --- a/src/Kook.Net.Rest/Net/Queue/GatewayBucket.cs +++ b/src/Kook.Net.Rest/Net/Queue/GatewayBucket.cs @@ -45,4 +45,4 @@ public GatewayBucket(GatewayBucketType type, BucketId id, int count, int seconds WindowCount = count; WindowSeconds = seconds; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Queue/RequestQueue.cs b/src/Kook.Net.Rest/Net/Queue/RequestQueue.cs index fa761091..28df1338 100644 --- a/src/Kook.Net.Rest/Net/Queue/RequestQueue.cs +++ b/src/Kook.Net.Rest/Net/Queue/RequestQueue.cs @@ -165,12 +165,12 @@ private async Task RunCleanup() while (!_cancelTokenSource.IsCancellationRequested) { var now = DateTimeOffset.UtcNow; - foreach (var bucket in _buckets.Where(x => x.Value is RequestBucket).Select(x => (RequestBucket) x.Value)) + foreach (var bucket in _buckets.Where(x => x.Value is RequestBucket).Select(x => (RequestBucket)x.Value)) { if ((now - bucket.LastAttemptAt).TotalMinutes > 1.0) { if (bucket.Id.IsHashBucket) - foreach (var redirectBucket in _buckets.Where(x => x.Value == bucket.Id).Select(x => (BucketId) x.Value)) + foreach (var redirectBucket in _buckets.Where(x => x.Value == bucket.Id).Select(x => (BucketId)x.Value)) _buckets.TryRemove(redirectBucket, out _); //remove redirections if hash bucket _buckets.TryRemove(bucket.Id, out _); } diff --git a/src/Kook.Net.Rest/Net/Queue/RequestQueueBucket.cs b/src/Kook.Net.Rest/Net/Queue/RequestQueueBucket.cs index abf1c305..466b7d6a 100644 --- a/src/Kook.Net.Rest/Net/Queue/RequestQueueBucket.cs +++ b/src/Kook.Net.Rest/Net/Queue/RequestQueueBucket.cs @@ -1,11 +1,11 @@ +using Kook.API; +using Kook.Rest; using System.Net; using System.Net.Mime; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; -using Kook.API; -using Kook.Rest; #if DEBUG_LIMITS using System.Diagnostics; #endif @@ -26,7 +26,7 @@ internal class RequestBucket public BucketId Id { get; private set; } public int WindowCount { get; private set; } public DateTimeOffset LastAttemptAt { get; private set; } - + public RequestBucket(RequestQueue queue, IRequest request, BucketId id) { _serializerOptions = new JsonSerializerOptions @@ -144,7 +144,7 @@ public async Task SendAsync(RestRequest request) if (response.MediaTypeHeader.MediaType == "application/json") { API.Rest.RestResponseBase responseBase = await JsonSerializer.DeserializeAsync(response.Stream, _serializerOptions); - if (responseBase?.Code > (KookErrorCode)0 ) + if (responseBase?.Code > (KookErrorCode)0) { throw new HttpException( response.StatusCode, @@ -411,35 +411,36 @@ private void UpdateRateLimit(int id, IRequest request, RateLimitInfo info, bool Debug.WriteLine($"[{id}] X-Rate-Limit-Remaining: " + info.Remaining.Value); _semaphore = info.Remaining.Value; }*/ -// if (info.RetryAfter.HasValue) -// { -// //RetryAfter is more accurate than Reset, where available -// resetTick = DateTimeOffset.UtcNow.AddSeconds(info.RetryAfter.Value); -// #if DEBUG_LIMITS -// Debug.WriteLine($"[{id}] Retry-After: {info.RetryAfter.Value} ({info.RetryAfter.Value} ms)"); -// #endif -// } - /*else*/ if (info.ResetAfter.HasValue) // && (request.Options.UseSystemClock.HasValue && !request.Options.UseSystemClock.Value) + // if (info.RetryAfter.HasValue) + // { + // //RetryAfter is more accurate than Reset, where available + // resetTick = DateTimeOffset.UtcNow.AddSeconds(info.RetryAfter.Value); + // #if DEBUG_LIMITS + // Debug.WriteLine($"[{id}] Retry-After: {info.RetryAfter.Value} ({info.RetryAfter.Value} ms)"); + // #endif + // } + /*else*/ + if (info.ResetAfter.HasValue) // && (request.Options.UseSystemClock.HasValue && !request.Options.UseSystemClock.Value) { resetTick = DateTimeOffset.UtcNow.Add(info.ResetAfter.Value); #if DEBUG_LIMITS Debug.WriteLine($"[{id}] Reset-After: {info.ResetAfter.Value} ({info.ResetAfter?.TotalMilliseconds} ms)"); #endif } -// else if (info.Reset.HasValue) -// { -// resetTick = info.Reset.Value.AddSeconds(info.Lag?.TotalSeconds ?? 1.0); -// -// /* millisecond precision makes this unnecessary, retaining in case of regression -// if (request.Options.IsReactionBucket) -// resetTick = DateTimeOffset.Now.AddMilliseconds(250); -// */ -// -// int diff = (int)(resetTick.Value - DateTimeOffset.UtcNow).TotalMilliseconds; -// #if DEBUG_LIMITS -// Debug.WriteLine($"[{id}] X-Rate-Limit-Reset: {info.Reset.Value.ToUnixTimeSeconds()} ({diff} ms, {info.Lag?.TotalMilliseconds} ms lag)"); -// #endif -// } + // else if (info.Reset.HasValue) + // { + // resetTick = info.Reset.Value.AddSeconds(info.Lag?.TotalSeconds ?? 1.0); + // + // /* millisecond precision makes this unnecessary, retaining in case of regression + // if (request.Options.IsReactionBucket) + // resetTick = DateTimeOffset.Now.AddMilliseconds(250); + // */ + // + // int diff = (int)(resetTick.Value - DateTimeOffset.UtcNow).TotalMilliseconds; + // #if DEBUG_LIMITS + // Debug.WriteLine($"[{id}] X-Rate-Limit-Reset: {info.Reset.Value.ToUnixTimeSeconds()} ({diff} ms, {info.Lag?.TotalMilliseconds} ms lag)"); + // #endif + // } else if (request.Options.IsClientBucket && Id != null) { resetTick = DateTimeOffset.UtcNow.AddSeconds(ClientBucket.Get(Id).WindowSeconds); diff --git a/src/Kook.Net.Rest/Net/Queue/Requests/JsonRestRequest.cs b/src/Kook.Net.Rest/Net/Queue/Requests/JsonRestRequest.cs index 9ac1f0b3..7680744c 100644 --- a/src/Kook.Net.Rest/Net/Queue/Requests/JsonRestRequest.cs +++ b/src/Kook.Net.Rest/Net/Queue/Requests/JsonRestRequest.cs @@ -1,4 +1,4 @@ -using Kook.Net.Rest; +using Kook.Net.Rest; namespace Kook.Net.Queue; @@ -16,4 +16,4 @@ public override async Task SendAsync() { return await Client.SendAsync(Method, Endpoint, Json, Options.CancelToken, Options.AuditLogReason, Options.RequestHeaders).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Queue/Requests/MultipartRestRequest.cs b/src/Kook.Net.Rest/Net/Queue/Requests/MultipartRestRequest.cs index 42477752..8520878f 100644 --- a/src/Kook.Net.Rest/Net/Queue/Requests/MultipartRestRequest.cs +++ b/src/Kook.Net.Rest/Net/Queue/Requests/MultipartRestRequest.cs @@ -5,7 +5,7 @@ namespace Kook.Net.Queue; internal class MultipartRestRequest : RestRequest { public IReadOnlyDictionary MultipartParams { get; } - + public MultipartRestRequest(IRestClient client, HttpMethod method, string endpoint, IReadOnlyDictionary multipartParams, RequestOptions options) : base(client, method, endpoint, options) { @@ -16,4 +16,4 @@ public override async Task SendAsync() { return await Client.SendAsync(Method, Endpoint, MultipartParams, Options.CancelToken, Options.AuditLogReason, Options.RequestHeaders).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Queue/Requests/RestRequest.cs b/src/Kook.Net.Rest/Net/Queue/Requests/RestRequest.cs index 64575fdf..00ffafbf 100644 --- a/src/Kook.Net.Rest/Net/Queue/Requests/RestRequest.cs +++ b/src/Kook.Net.Rest/Net/Queue/Requests/RestRequest.cs @@ -30,4 +30,4 @@ public virtual async Task SendAsync() { return await Client.SendAsync(Method, Endpoint, Options.CancelToken, Options.AuditLogReason, Options.RequestHeaders).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/Queue/Requests/WebSocketRequest.cs b/src/Kook.Net.Rest/Net/Queue/Requests/WebSocketRequest.cs index 7f836305..e0779280 100644 --- a/src/Kook.Net.Rest/Net/Queue/Requests/WebSocketRequest.cs +++ b/src/Kook.Net.Rest/Net/Queue/Requests/WebSocketRequest.cs @@ -34,4 +34,4 @@ public async Task SendAsync() { await Client.SendAsync(Data, 0, Data.Length, IsText).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.Rest/Net/RateLimitInfo.cs b/src/Kook.Net.Rest/Net/RateLimitInfo.cs index a92c9505..724e16a7 100644 --- a/src/Kook.Net.Rest/Net/RateLimitInfo.cs +++ b/src/Kook.Net.Rest/Net/RateLimitInfo.cs @@ -39,9 +39,9 @@ internal RateLimitInfo(Dictionary headers, string endpoint) Endpoint = endpoint; IsGlobal = headers.ContainsKey("X-Rate-Limit-Global"); - Limit = headers.TryGetValue("X-Rate-Limit-Limit", out string temp) && + Limit = headers.TryGetValue("X-Rate-Limit-Limit", out string temp) && int.TryParse(temp, NumberStyles.None, CultureInfo.InvariantCulture, out var limit) ? limit : (int?)null; - Remaining = headers.TryGetValue("X-Rate-Limit-Remaining", out temp) && + Remaining = headers.TryGetValue("X-Rate-Limit-Remaining", out temp) && int.TryParse(temp, NumberStyles.None, CultureInfo.InvariantCulture, out var remaining) ? remaining : (int?)null; // RetryAfter = headers.TryGetValue("Retry-After", out temp) && // int.TryParse(temp, NumberStyles.None, CultureInfo.InvariantCulture, out var retryAfter) ? retryAfter : (int?)null; @@ -53,4 +53,4 @@ internal RateLimitInfo(Dictionary headers, string endpoint) Lag = headers.TryGetValue("Date", out temp) && DateTimeOffset.TryParse(temp, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) ? DateTimeOffset.UtcNow - date : (TimeSpan?)null; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/ChannelDeleteEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/ChannelDeleteEvent.cs index 088de278..99064122 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/ChannelDeleteEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/ChannelDeleteEvent.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -7,8 +7,8 @@ internal class ChannelDeleteEvent { [JsonPropertyName("id")] public ulong ChannelId { get; set; } - + [JsonPropertyName("deleted_at")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset DeletedAt { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/DirectMessageDeleteEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/DirectMessageDeleteEvent.cs index cdc146ba..0e3b900c 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/DirectMessageDeleteEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/DirectMessageDeleteEvent.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -10,15 +10,15 @@ internal class DirectMessageDeleteEvent [JsonPropertyName("target_id")] public ulong UserId { get; set; } - - [JsonPropertyName("msg_id")] + + [JsonPropertyName("msg_id")] public Guid MessageId { get; set; } - - [JsonPropertyName("deleted_at")] + + [JsonPropertyName("deleted_at")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset DeletedAt { get; set; } - + [JsonPropertyName("chat_code")] [JsonConverter(typeof(ChatCodeConverter))] public Guid ChatCode { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/DirectMessageUpdateEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/DirectMessageUpdateEvent.cs index 5d07e126..252a9cab 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/DirectMessageUpdateEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/DirectMessageUpdateEvent.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -11,18 +11,18 @@ internal class DirectMessageUpdateEvent // self user id in fact [JsonPropertyName("target_id")] public ulong UserId { get; set; } - - [JsonPropertyName("msg_id")] + + [JsonPropertyName("msg_id")] public Guid MessageId { get; set; } - - [JsonPropertyName("content")] + + [JsonPropertyName("content")] public string Content { get; set; } - - [JsonPropertyName("updated_at")] + + [JsonPropertyName("updated_at")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset UpdatedAt { get; set; } - + [JsonPropertyName("chat_code")] [JsonConverter(typeof(ChatCodeConverter))] public Guid ChatCode { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GatewayEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/GatewayEvent.cs index 630b5909..1f4142ea 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GatewayEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GatewayEvent.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -26,4 +26,4 @@ internal class GatewayEvent [JsonPropertyName("nonce")] public string Nonce { get; set; } [JsonPropertyName("extra")] public object ExtraData { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GatewayGroupMessageExtraData.cs b/src/Kook.Net.WebSocket/API/Gateway/GatewayGroupMessageExtraData.cs index 566a49e6..981b6195 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GatewayGroupMessageExtraData.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GatewayGroupMessageExtraData.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -8,7 +8,7 @@ internal class GatewayGroupMessageExtraData [JsonPropertyName("type")] [JsonConverter(typeof(MessageTypeConverter))] public MessageType Type { get; set; } - + [JsonPropertyName("guild_id")] public ulong GuildId { get; set; } @@ -35,10 +35,10 @@ internal class GatewayGroupMessageExtraData [JsonPropertyName("quote")] public Quote Quote { get; set; } - + [JsonPropertyName("attachments")] public Attachment Attachment { get; set; } - + [JsonPropertyName("kmarkdown")] public KMarkdownInfo KMarkdownInfo { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GatewayHelloPayload.cs b/src/Kook.Net.WebSocket/API/Gateway/GatewayHelloPayload.cs index d2975c7b..3f51204f 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GatewayHelloPayload.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GatewayHelloPayload.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -7,8 +7,8 @@ internal class GatewayHelloPayload { [JsonPropertyName("code")] public KookErrorCode Code { get; set; } - + [JsonPropertyName("session_id")] // [JsonConverter(typeof(GuidConverter))] public Guid SessionId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GatewayPersonMessageExtraData.cs b/src/Kook.Net.WebSocket/API/Gateway/GatewayPersonMessageExtraData.cs index b473522e..f264058d 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GatewayPersonMessageExtraData.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GatewayPersonMessageExtraData.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -8,26 +8,26 @@ internal class GatewayPersonMessageExtraData [JsonPropertyName("type")] [JsonConverter(typeof(MessageTypeConverter))] public MessageType Type { get; set; } - + [JsonPropertyName("code")] [JsonConverter(typeof(ChatCodeConverter))] public Guid Code { get; set; } [JsonPropertyName("author")] public User Author { get; set; } - + [JsonPropertyName("nonce")] public string Nonce { get; set; } [JsonPropertyName("last_msg_content")] public string LastMessageContent { get; set; } - + [JsonPropertyName("quote")] public Quote Quote { get; set; } - + [JsonPropertyName("attachments")] public Attachment Attachment { get; set; } - + [JsonPropertyName("kmarkdown")] public KMarkdownInfo KMarkdownInfo { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GatewayReconnectPayload.cs b/src/Kook.Net.WebSocket/API/Gateway/GatewayReconnectPayload.cs index d14c8ecc..e343b665 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GatewayReconnectPayload.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GatewayReconnectPayload.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -7,7 +7,7 @@ internal class GatewayReconnectPayload { [JsonPropertyName("code")] public KookErrorCode Code { get; set; } - + [JsonPropertyName("err")] public string Message { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GatewaySocketFrame.cs b/src/Kook.Net.WebSocket/API/Gateway/GatewaySocketFrame.cs index 0308a751..2e608620 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GatewaySocketFrame.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GatewaySocketFrame.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -15,4 +15,4 @@ internal class GatewaySocketFrame [JsonPropertyName("d")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public object Payload { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GatewaySocketFrameType.cs b/src/Kook.Net.WebSocket/API/Gateway/GatewaySocketFrameType.cs index 02ee5014..89f3c3ae 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GatewaySocketFrameType.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GatewaySocketFrameType.cs @@ -9,4 +9,4 @@ internal enum GatewaySocketFrameType Resume, Reconnect, ResumeAck -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GatewaySystemEventExtraData.cs b/src/Kook.Net.WebSocket/API/Gateway/GatewaySystemEventExtraData.cs index 39f515fc..3be51668 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GatewaySystemEventExtraData.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GatewaySystemEventExtraData.cs @@ -6,7 +6,7 @@ internal class GatewaySystemEventExtraData { [JsonPropertyName("type")] public string Type { get; set; } - + [JsonPropertyName("body")] public object Body { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GuildBanEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/GuildBanEvent.cs index 0ef8e1c5..d4171c5f 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GuildBanEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GuildBanEvent.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -7,7 +7,7 @@ internal class GuildBanEvent { [JsonPropertyName("operator_id")] public ulong OperatorUserId { get; set; } - + [JsonPropertyName("user_id")] public ulong[] UserIds { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GuildEmojiEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/GuildEmojiEvent.cs index c656f8c1..86e64363 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GuildEmojiEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GuildEmojiEvent.cs @@ -12,4 +12,4 @@ internal class GuildEmojiEvent [JsonPropertyName("emoji_type")] public EmojiType Type { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GuildEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/GuildEvent.cs index c50fdd26..2c647c8f 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GuildEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GuildEvent.cs @@ -1,6 +1,6 @@ +using Kook.Net.Converters; using System.Security.Principal; using System.Text.Json.Serialization; -using Kook.Net.Converters; namespace Kook.API.Gateway; @@ -8,48 +8,48 @@ internal class GuildEvent { [JsonPropertyName("id")] public ulong GuildId { get; set; } - + [JsonPropertyName("name")] public string Name { get; set; } - + [JsonPropertyName("user_id")] public ulong UserId { get; set; } - + [JsonPropertyName("icon")] public string Icon { get; set; } - + [JsonPropertyName("notify_type")] public NotifyType NotifyType { get; set; } - [JsonPropertyName("region")] + [JsonPropertyName("region")] public string Region { get; set; } - + [JsonPropertyName("enable_open")] [JsonConverter(typeof(NumberBooleanConverter))] public bool EnableOpen { get; set; } - + [JsonPropertyName("open_id")] [JsonConverter(typeof(NullableUInt32Converter))] public uint? OpenId { get; set; } - + [JsonPropertyName("default_channel_id")] public ulong DefaultChannelId { get; set; } [JsonPropertyName("welcome_channel_id")] public ulong WelcomeChannelId { get; set; } - [JsonPropertyName("banner")] + [JsonPropertyName("banner")] public string Banner { get; set; } - - [JsonPropertyName("banner_status")] + + [JsonPropertyName("banner_status")] public int BannerStatus { get; set; } - - [JsonPropertyName("custom_id")] + + [JsonPropertyName("custom_id")] public string CustomId { get; set; } - + [JsonPropertyName("boost_num")] public int BoostSubscriptionCount { get; set; } - + [JsonPropertyName("buffer_boost_num")] public int BufferBoostSubscriptionCount { get; set; } @@ -58,4 +58,4 @@ internal class GuildEvent [JsonPropertyName("status")] public int Status { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GuildMemberAddEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/GuildMemberAddEvent.cs index 24a1044f..542b3b18 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GuildMemberAddEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GuildMemberAddEvent.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -7,8 +7,8 @@ internal class GuildMemberAddEvent { [JsonPropertyName("user_id")] public ulong UserId { get; set; } - + [JsonPropertyName("joined_at")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset JoinedAt { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GuildMemberOfflineEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/GuildMemberOfflineEvent.cs index 6fb2d54b..3068cd5b 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GuildMemberOfflineEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GuildMemberOfflineEvent.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -7,11 +7,11 @@ internal class GuildMemberOfflineEvent { [JsonPropertyName("user_id")] public ulong UserId { get; set; } - + [JsonPropertyName("event_time")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset OfflineAt { get; set; } [JsonPropertyName("guilds")] public ulong[] CommonGuilds { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GuildMemberOnlineEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/GuildMemberOnlineEvent.cs index 58f68533..a36a5a8b 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GuildMemberOnlineEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GuildMemberOnlineEvent.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -7,11 +7,11 @@ internal class GuildMemberOnlineEvent { [JsonPropertyName("user_id")] public ulong UserId { get; set; } - + [JsonPropertyName("event_time")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset OnlineAt { get; set; } [JsonPropertyName("guilds")] public ulong[] CommonGuilds { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GuildMemberRemoveEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/GuildMemberRemoveEvent.cs index da6ab301..92365eff 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GuildMemberRemoveEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GuildMemberRemoveEvent.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -7,8 +7,8 @@ internal class GuildMemberRemoveEvent { [JsonPropertyName("user_id")] public ulong UserId { get; set; } - + [JsonPropertyName("exited_at")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset ExitedAt { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/GuildMemberUpdateEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/GuildMemberUpdateEvent.cs index 9a75e1a9..fd6cf553 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/GuildMemberUpdateEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/GuildMemberUpdateEvent.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -7,7 +7,7 @@ internal class GuildMemberUpdateEvent { [JsonPropertyName("user_id")] public ulong UserId { get; set; } - + [JsonPropertyName("nickname")] public string Nickname { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/KMarkdownInfo.cs b/src/Kook.Net.WebSocket/API/Gateway/KMarkdownInfo.cs index d5edc8a4..2b160934 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/KMarkdownInfo.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/KMarkdownInfo.cs @@ -6,11 +6,11 @@ internal class KMarkdownInfo { [JsonPropertyName("raw_content")] public string RawContent { get; set; } - + [JsonPropertyName("mention")] public ulong[] MentionedUserIds { get; set; } [JsonPropertyName("mention_part")] public MentionedUser[] MentionedUsers { get; set; } [JsonPropertyName("item_part")] public Poke[] Pokes { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/MessageButtonClickEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/MessageButtonClickEvent.cs index 10007daa..54262f37 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/MessageButtonClickEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/MessageButtonClickEvent.cs @@ -6,18 +6,18 @@ internal class MessageButtonClickEvent { [JsonPropertyName("value")] public string Value { get; set; } - + [JsonPropertyName("msg_id")] public Guid MessageId { get; set; } - + [JsonPropertyName("user_id")] public ulong UserId { get; set; } - + [JsonPropertyName("target_id")] public ulong ChannelId { get; set; } - + [JsonPropertyName("user_info")] public User User { get; set; } [JsonPropertyName("guild_id")] public ulong? GuildId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/MessageDeleteEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/MessageDeleteEvent.cs index 207c61a7..4d9e9393 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/MessageDeleteEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/MessageDeleteEvent.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -7,7 +7,7 @@ internal class MessageDeleteEvent { [JsonPropertyName("channel_id")] public ulong ChannelId { get; set; } - + [JsonPropertyName("msg_id")] public Guid MessageId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/MessageUpdateEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/MessageUpdateEvent.cs index 4cd813e2..a393a382 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/MessageUpdateEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/MessageUpdateEvent.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -7,13 +7,13 @@ internal class MessageUpdateEvent { [JsonPropertyName("channel_id")] public ulong ChannelId { get; set; } - + [JsonPropertyName("content")] public string Content { get; set; } - + [JsonPropertyName("mention")] public ulong[] Mention { get; set; } - + [JsonPropertyName("mention_all")] public bool MentionAll { get; set; } @@ -22,11 +22,11 @@ internal class MessageUpdateEvent [JsonPropertyName("mention_roles")] public uint[] MentionRoles { get; set; } - - [JsonPropertyName("updated_at")] + + [JsonPropertyName("updated_at")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset UpdatedAt { get; set; } - + [JsonPropertyName("msg_id")] public Guid MessageId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/PinnedMessageEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/PinnedMessageEvent.cs index d8187ec2..651c2235 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/PinnedMessageEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/PinnedMessageEvent.cs @@ -1,17 +1,17 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; internal class PinnedMessageEvent { - + [JsonPropertyName("channel_id")] public ulong ChannelId { get; set; } - + [JsonPropertyName("operator_id")] public ulong OperatorUserId { get; set; } - + [JsonPropertyName("msg_id")] public Guid MessageId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/PrivateReaction.cs b/src/Kook.Net.WebSocket/API/Gateway/PrivateReaction.cs index bf0ff52e..12b761f1 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/PrivateReaction.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/PrivateReaction.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -15,4 +15,4 @@ internal class PrivateReaction public ulong UserId { get; set; } [JsonPropertyName("emoji")] public Emoji Emoji { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/Reaction.cs b/src/Kook.Net.WebSocket/API/Gateway/Reaction.cs index 92755e23..8b7f92fd 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/Reaction.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/Reaction.cs @@ -13,4 +13,4 @@ internal class Reaction public ulong UserId { get; set; } [JsonPropertyName("emoji")] public Emoji Emoji { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/SelfGuildEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/SelfGuildEvent.cs index e9d12e78..6d2c21a7 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/SelfGuildEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/SelfGuildEvent.cs @@ -6,4 +6,4 @@ internal class SelfGuildEvent { [JsonPropertyName("guild_id")] public ulong GuildId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/UnpinnedMessageEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/UnpinnedMessageEvent.cs index 2748f9ca..75ba5a39 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/UnpinnedMessageEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/UnpinnedMessageEvent.cs @@ -1,17 +1,17 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; internal class UnpinnedMessageEvent { - + [JsonPropertyName("channel_id")] public ulong ChannelId { get; set; } - + [JsonPropertyName("operator_id")] public ulong OperatorUserId { get; set; } - + [JsonPropertyName("msg_id")] public Guid MessageId { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/UserUpdateEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/UserUpdateEvent.cs index b2cfc133..8c022ddd 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/UserUpdateEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/UserUpdateEvent.cs @@ -6,8 +6,8 @@ internal class UserUpdateEvent { [JsonPropertyName("user_id")] public ulong UserId { get; set; } - + [JsonPropertyName("username")] public string Username { get; set; } - + [JsonPropertyName("avatar")] public string Avatar { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Gateway/UserVoiceEvent.cs b/src/Kook.Net.WebSocket/API/Gateway/UserVoiceEvent.cs index 19cf6a66..287fb7bc 100644 --- a/src/Kook.Net.WebSocket/API/Gateway/UserVoiceEvent.cs +++ b/src/Kook.Net.WebSocket/API/Gateway/UserVoiceEvent.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Gateway; @@ -7,11 +7,11 @@ internal class UserVoiceEvent { [JsonPropertyName("user_id")] public ulong UserId { get; set; } - + [JsonPropertyName("channel_id")] public ulong ChannelId { get; set; } - + [JsonPropertyName("joined_at")] [JsonConverter(typeof(DateTimeOffsetUnixTimeMillisecondsConverter))] public DateTimeOffset At { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Voice/CreatePlainTransportParams.cs b/src/Kook.Net.WebSocket/API/Voice/CreatePlainTransportParams.cs index 25dbe42c..de2365dd 100644 --- a/src/Kook.Net.WebSocket/API/Voice/CreatePlainTransportParams.cs +++ b/src/Kook.Net.WebSocket/API/Voice/CreatePlainTransportParams.cs @@ -6,10 +6,10 @@ internal class CreatePlainTransportParams { [JsonPropertyName("comedia")] public bool Comedia { get; set; } - + [JsonPropertyName("rtcpMux")] public bool RTCPMultiplexing { get; set; } [JsonPropertyName("type")] public string Type { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Voice/CreatePlainTransportResponse.cs b/src/Kook.Net.WebSocket/API/Voice/CreatePlainTransportResponse.cs index f65845dd..8e01abe3 100644 --- a/src/Kook.Net.WebSocket/API/Voice/CreatePlainTransportResponse.cs +++ b/src/Kook.Net.WebSocket/API/Voice/CreatePlainTransportResponse.cs @@ -6,13 +6,13 @@ internal class CreatePlainTransportResponse { [JsonPropertyName("id")] public Guid Id { get; set; } - + [JsonPropertyName("ip")] public string Ip { get; set; } - + [JsonPropertyName("port")] public int Port { get; set; } [JsonPropertyName("rtcpPort")] public string RTCPPort { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Voice/JoinParams.cs b/src/Kook.Net.WebSocket/API/Voice/JoinParams.cs index 5e654a4c..af1601d1 100644 --- a/src/Kook.Net.WebSocket/API/Voice/JoinParams.cs +++ b/src/Kook.Net.WebSocket/API/Voice/JoinParams.cs @@ -6,4 +6,4 @@ internal class JoinParams { [JsonPropertyName("displayName")] public string DisplayName { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Voice/ProduceParams.cs b/src/Kook.Net.WebSocket/API/Voice/ProduceParams.cs index f803b698..dbd24992 100644 --- a/src/Kook.Net.WebSocket/API/Voice/ProduceParams.cs +++ b/src/Kook.Net.WebSocket/API/Voice/ProduceParams.cs @@ -9,19 +9,19 @@ public ProduceParams(Guid transportId) { TransportId = transportId; } - + [JsonPropertyName("appData")] public object AppData { get; set; } - + [JsonPropertyName("kind")] public string Kind { get; set; } - + [JsonPropertyName("peerId")] public string PeerId { get; set; } - + [JsonPropertyName("rtpParameters")] public RTPParameters RTPParameters { get; set; } - + [JsonPropertyName("transportId")] public Guid TransportId { get; set; } } @@ -30,7 +30,7 @@ internal class RTPParameters { [JsonPropertyName("codecs")] public Codec[] Codecs { get; set; } - + [JsonPropertyName("encodings")] public Encoding[] Encodings { get; set; } } @@ -44,16 +44,16 @@ internal class Codec { [JsonPropertyName("channels")] public int Channels { get; set; } - + [JsonPropertyName("clockRate")] public int ClockRate { get; set; } - + [JsonPropertyName("mimeType")] public string MimeType { get; set; } - + [JsonPropertyName("parameters")] public Parameters Parameters { get; set; } - + [JsonPropertyName("payloadType")] public int PayloadType { get; set; } } @@ -62,4 +62,4 @@ internal class Parameters { [JsonPropertyName("sprop-stereo")] public int SenderProduceStereo { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Voice/VoiceSocketFrameType.cs b/src/Kook.Net.WebSocket/API/Voice/VoiceSocketFrameType.cs index 4fcec146..32569f3a 100644 --- a/src/Kook.Net.WebSocket/API/Voice/VoiceSocketFrameType.cs +++ b/src/Kook.Net.WebSocket/API/Voice/VoiceSocketFrameType.cs @@ -6,4 +6,4 @@ internal enum VoiceSocketFrameType Join, CreatePlainTransport, Produce -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Voice/VoiceSocketRequestFrame.cs b/src/Kook.Net.WebSocket/API/Voice/VoiceSocketRequestFrame.cs index c4953948..def4a5ac 100644 --- a/src/Kook.Net.WebSocket/API/Voice/VoiceSocketRequestFrame.cs +++ b/src/Kook.Net.WebSocket/API/Voice/VoiceSocketRequestFrame.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Voice; @@ -8,13 +8,13 @@ internal class VoiceSocketRequestFrame [JsonPropertyName("method")] [JsonConverter(typeof(VoiceSocketFrameTypeConverter))] public VoiceSocketFrameType Type { get; set; } - + [JsonPropertyName("id")] public uint Id { get; set; } [JsonPropertyName("request")] public bool Request { get; set; } - + [JsonPropertyName("data")] public object Payload { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/API/Voice/VoiceSocketResponseFrame.cs b/src/Kook.Net.WebSocket/API/Voice/VoiceSocketResponseFrame.cs index dba1fc10..79a62d72 100644 --- a/src/Kook.Net.WebSocket/API/Voice/VoiceSocketResponseFrame.cs +++ b/src/Kook.Net.WebSocket/API/Voice/VoiceSocketResponseFrame.cs @@ -1,5 +1,5 @@ -using System.Text.Json.Serialization; using Kook.Net.Converters; +using System.Text.Json.Serialization; namespace Kook.API.Voice; @@ -7,13 +7,13 @@ internal class VoiceSocketResponseFrame { [JsonPropertyName("response")] public bool Response { get; set; } - + [JsonPropertyName("id")] public uint Id { get; set; } - + [JsonPropertyName("ok")] public bool Okay { get; set; } - + [JsonPropertyName("data")] public object Payload { get; set; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/AssemblyInfo.cs b/src/Kook.Net.WebSocket/AssemblyInfo.cs index fea40eb5..4c04a555 100644 --- a/src/Kook.Net.WebSocket/AssemblyInfo.cs +++ b/src/Kook.Net.WebSocket/AssemblyInfo.cs @@ -2,4 +2,4 @@ [assembly: InternalsVisibleTo("Kook.Net.Experimental")] [assembly: InternalsVisibleTo("Kook.Net.Tests.Unit")] -[assembly: InternalsVisibleTo("Kook.Net.Tests.Integration")] \ No newline at end of file +[assembly: InternalsVisibleTo("Kook.Net.Tests.Integration")] diff --git a/src/Kook.Net.WebSocket/Audio/AudioClient.Events.cs b/src/Kook.Net.WebSocket/Audio/AudioClient.Events.cs index f4bf30a0..f8dec6e4 100644 --- a/src/Kook.Net.WebSocket/Audio/AudioClient.Events.cs +++ b/src/Kook.Net.WebSocket/Audio/AudioClient.Events.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; namespace Kook.Audio; @@ -47,4 +47,4 @@ public event Func SpeakingUpdated remove => _speakingUpdatedEvent.Remove(value); } private readonly AsyncEvent> _speakingUpdatedEvent = new AsyncEvent>(); -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/AudioClient.cs b/src/Kook.Net.WebSocket/Audio/AudioClient.cs index 01fe3e33..7b3f37f0 100644 --- a/src/Kook.Net.WebSocket/Audio/AudioClient.cs +++ b/src/Kook.Net.WebSocket/Audio/AudioClient.cs @@ -1,18 +1,18 @@ using Kook.API.Voice; +using Kook.Audio.Streams; using Kook.Logging; using Kook.Net.Converters; using Kook.WebSocket; using System; using System.Collections.Concurrent; +using System.Collections.Generic; using System.Linq; using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Collections.Generic; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; -using Kook.Audio.Streams; +using System.Threading; +using System.Threading.Tasks; namespace Kook.Audio; @@ -81,7 +81,7 @@ internal AudioClient(SocketGuild guild, int clientId, ulong channelId) _connection.Disconnected += (ex, recon) => _disconnectedEvent.InvokeAsync(ex); _heartbeatTimes = new ConcurrentQueue(); _keepaliveTimes = new ConcurrentQueue>(); - _ssrcGenerator = new Random((int) DateTimeOffset.UtcNow.Ticks); + _ssrcGenerator = new Random((int)DateTimeOffset.UtcNow.Ticks); _ssrcMap = new ConcurrentDictionary(); _streams = new ConcurrentDictionary(); _sentFrames = new ConcurrentDictionary(); @@ -148,7 +148,8 @@ private async Task OnDisconnectingAsync(Exception ex) await keepaliveTask.ConfigureAwait(false); _keepaliveTask = null; - while (_heartbeatTimes.TryDequeue(out _)) { } + while (_heartbeatTimes.TryDequeue(out _)) + { } _lastMessageTime = 0; await ClearInputStreamsAsync().ConfigureAwait(false); @@ -230,42 +231,42 @@ private async Task ProcessMessageAsync(uint id, bool okay, object payload) _lastMessageTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); if (!_sentFrames.TryRemove(id, out VoiceSocketFrameType type) || !okay) await _audioLogger.ErrorAsync($"Error handling event with id {id}").ConfigureAwait(false); - + try { switch (type) { case VoiceSocketFrameType.GetRouterRtpCapabilities: - { - await _audioLogger.DebugAsync($"Received Response of {type}").ConfigureAwait(false); - await ApiClient.SendJoinRequestAsync(); - } + { + await _audioLogger.DebugAsync($"Received Response of {type}").ConfigureAwait(false); + await ApiClient.SendJoinRequestAsync(); + } break; case VoiceSocketFrameType.Join: - { - await _audioLogger.DebugAsync($"Received Response of {type}").ConfigureAwait(false); - await ApiClient.SendCreatePlainTransportRequestAsync().ConfigureAwait(false); - } + { + await _audioLogger.DebugAsync($"Received Response of {type}").ConfigureAwait(false); + await ApiClient.SendCreatePlainTransportRequestAsync().ConfigureAwait(false); + } break; case VoiceSocketFrameType.CreatePlainTransport: - { - await _audioLogger.DebugAsync($"Received Response of {type}").ConfigureAwait(false); - var data = ((JsonElement) payload).Deserialize(_serializerOptions); - ApiClient.SetUdpEndpoint(data.Ip, data.Port); - _ssrc = (uint) _ssrcGenerator.Next(1, ushort.MaxValue); - await ApiClient.SendProduceRequestAsync(data.Id, _ssrc).ConfigureAwait(false); - } + { + await _audioLogger.DebugAsync($"Received Response of {type}").ConfigureAwait(false); + var data = ((JsonElement)payload).Deserialize(_serializerOptions); + ApiClient.SetUdpEndpoint(data.Ip, data.Port); + _ssrc = (uint)_ssrcGenerator.Next(1, ushort.MaxValue); + await ApiClient.SendProduceRequestAsync(data.Id, _ssrc).ConfigureAwait(false); + } break; case VoiceSocketFrameType.Produce: - { - await _audioLogger.DebugAsync($"Received Response of {type}").ConfigureAwait(false); - // _heartbeatTask = RunHeartbeatAsync(_connection.CancelToken); - _keepaliveTask = RunKeepaliveAsync(5000, _connection.CancelToken); + { + await _audioLogger.DebugAsync($"Received Response of {type}").ConfigureAwait(false); + // _heartbeatTask = RunHeartbeatAsync(_connection.CancelToken); + _keepaliveTask = RunKeepaliveAsync(5000, _connection.CancelToken); - var _ = _connection.CompleteAsync(); - } + var _ = _connection.CompleteAsync(); + } break; - + // case VoiceOpCode.Ready: // { // await _audioLogger.DebugAsync("Received Ready").ConfigureAwait(false); @@ -525,4 +526,4 @@ internal void Dispose(bool disposing) } /// public void Dispose() => Dispose(true); -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Opus/OpusApplication.cs b/src/Kook.Net.WebSocket/Audio/Opus/OpusApplication.cs index eb35cab0..a5f69232 100644 --- a/src/Kook.Net.WebSocket/Audio/Opus/OpusApplication.cs +++ b/src/Kook.Net.WebSocket/Audio/Opus/OpusApplication.cs @@ -1,8 +1,8 @@ -namespace Kook.Audio; +namespace Kook.Audio; internal enum OpusApplication : int { Voice = 2048, MusicOrMixed = 2049, LowLatency = 2051 -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Opus/OpusConverter.cs b/src/Kook.Net.WebSocket/Audio/Opus/OpusConverter.cs index 4656f64e..c5cec4e1 100644 --- a/src/Kook.Net.WebSocket/Audio/Opus/OpusConverter.cs +++ b/src/Kook.Net.WebSocket/Audio/Opus/OpusConverter.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Kook.Audio; @@ -15,7 +15,7 @@ internal abstract class OpusConverter : IDisposable public const int FrameSamplesPerChannel = SamplingRate / 1000 * FrameMillis; public const int FrameSamples = FrameSamplesPerChannel * Channels; public const int FrameBytes = FrameSamplesPerChannel * SampleBytes; - + protected bool _isDisposed = false; protected virtual void Dispose(bool disposing) @@ -32,7 +32,7 @@ public void Dispose() Dispose(true); GC.SuppressFinalize(this); } - + protected static void CheckError(int result) { if (result < 0) @@ -43,4 +43,4 @@ protected static void CheckError(OpusError error) if ((int)error < 0) throw new Exception($"Opus Error: {error}"); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Opus/OpusCtl.cs b/src/Kook.Net.WebSocket/Audio/Opus/OpusCtl.cs index 4600d51a..6bb311d6 100644 --- a/src/Kook.Net.WebSocket/Audio/Opus/OpusCtl.cs +++ b/src/Kook.Net.WebSocket/Audio/Opus/OpusCtl.cs @@ -1,4 +1,4 @@ -namespace Kook.Audio; +namespace Kook.Audio; //https://github.com/gcp/opus/blob/master/include/opus_defines.h internal enum OpusCtl : int @@ -8,4 +8,4 @@ internal enum OpusCtl : int SetInbandFEC = 4012, SetPacketLossPercent = 4014, SetSignal = 4024 -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Opus/OpusDecoder.cs b/src/Kook.Net.WebSocket/Audio/Opus/OpusDecoder.cs index d026624f..aa5e9ae0 100644 --- a/src/Kook.Net.WebSocket/Audio/Opus/OpusDecoder.cs +++ b/src/Kook.Net.WebSocket/Audio/Opus/OpusDecoder.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Runtime.InteropServices; namespace Kook.Audio; @@ -19,7 +19,7 @@ public OpusDecoder() _ptr = CreateDecoder(SamplingRate, Channels, out var error); CheckError(error); } - + public unsafe int DecodeFrame(byte[] input, int inputOffset, int inputCount, byte[] output, int outputOffset, bool decodeFEC) { int result = 0; @@ -39,4 +39,4 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Opus/OpusEncoder.cs b/src/Kook.Net.WebSocket/Audio/Opus/OpusEncoder.cs index f904e168..489396b6 100644 --- a/src/Kook.Net.WebSocket/Audio/Opus/OpusEncoder.cs +++ b/src/Kook.Net.WebSocket/Audio/Opus/OpusEncoder.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Runtime.InteropServices; namespace Kook.Audio; @@ -13,9 +13,9 @@ internal unsafe class OpusEncoder : OpusConverter private static extern int Encode(IntPtr st, byte* pcm, int frame_size, byte* data, int max_data_bytes); [DllImport("opus", EntryPoint = "opus_encoder_ctl", CallingConvention = CallingConvention.Cdecl)] private static extern OpusError EncoderCtl(IntPtr st, OpusCtl request, int value); - + public AudioApplication Application { get; } - public int BitRate { get;} + public int BitRate { get; } public OpusEncoder(int bitrate, AudioApplication application, int packetLoss) { @@ -72,4 +72,4 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Opus/OpusError.cs b/src/Kook.Net.WebSocket/Audio/Opus/OpusError.cs index 694e0fd2..7fc06122 100644 --- a/src/Kook.Net.WebSocket/Audio/Opus/OpusError.cs +++ b/src/Kook.Net.WebSocket/Audio/Opus/OpusError.cs @@ -1,4 +1,4 @@ -namespace Kook.Audio; +namespace Kook.Audio; internal enum OpusError : int { @@ -10,4 +10,4 @@ internal enum OpusError : int Unimplemented = -5, InvalidState = -6, AllocFail = -7 -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Opus/OpusSignal.cs b/src/Kook.Net.WebSocket/Audio/Opus/OpusSignal.cs index 32545438..047675b5 100644 --- a/src/Kook.Net.WebSocket/Audio/Opus/OpusSignal.cs +++ b/src/Kook.Net.WebSocket/Audio/Opus/OpusSignal.cs @@ -5,4 +5,4 @@ internal enum OpusSignal : int Auto = -1000, Voice = 3001, Music = 3002, -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Sodium/SecretBox.cs b/src/Kook.Net.WebSocket/Audio/Sodium/SecretBox.cs index 073665b4..e4c0d507 100644 --- a/src/Kook.Net.WebSocket/Audio/Sodium/SecretBox.cs +++ b/src/Kook.Net.WebSocket/Audio/Sodium/SecretBox.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Runtime.InteropServices; namespace Kook.Audio; @@ -32,4 +32,4 @@ public static int Decrypt(byte[] input, int inputOffset, int inputLength, byte[] return inputLength - 16; } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs index b14e6300..75a788aa 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs @@ -189,4 +189,4 @@ public override Task ClearAsync(CancellationToken cancelToken) while (_queuedFrames.TryDequeue(out _)); return Task.Delay(0); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Streams/InputStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/InputStream.cs index d1e10c6f..dd398053 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/InputStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/InputStream.cs @@ -108,4 +108,4 @@ protected override void Dispose(bool isDisposing) base.Dispose(isDisposing); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Streams/JitterBuffer.cs b/src/Kook.Net.WebSocket/Audio/Streams/JitterBuffer.cs index 265031b7..6b3c6ffa 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/JitterBuffer.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/JitterBuffer.cs @@ -243,4 +243,4 @@ public override Task ClearAsync(CancellationToken cancelToken) return Task.Delay(0); } } -}*/ \ No newline at end of file +}*/ diff --git a/src/Kook.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs index 75110f02..1588a890 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs @@ -26,7 +26,7 @@ public OpusDecodeStream(AudioStream next) public override void WriteHeader(ushort seq, uint timestamp, bool missed) { if (_hasHeader) - throw new InvalidOperationException("Header received with no payload."); + throw new InvalidOperationException("Header received with no payload."); _hasHeader = true; _nextMissed = missed; @@ -75,4 +75,4 @@ protected override void Dispose(bool disposing) } base.Dispose(disposing); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs index d7cb88a4..53eeb749 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs @@ -15,7 +15,7 @@ public class OpusEncodeStream : AudioOutStream private int _partialFramePos; private ushort _seq; private uint _timestamp; - + public OpusEncodeStream(AudioStream next, int bitrate, AudioApplication application, int packetLoss) { _next = next; @@ -96,4 +96,4 @@ protected override void Dispose(bool disposing) } base.Dispose(disposing); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Streams/OutputStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/OutputStream.cs index 250f0fc9..290cb1d5 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/OutputStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/OutputStream.cs @@ -13,11 +13,11 @@ internal OutputStream(KookVoiceAPIClient client) { _client = client; } - + public override void WriteHeader(ushort seq, uint timestamp, bool missed) { } //Ignore public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken) { cancelToken.ThrowIfCancellationRequested(); await _client.SendAsync(buffer, offset, count).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Streams/RTPReadStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/RTPReadStream.cs index 44d39dfb..af541b44 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/RTPReadStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/RTPReadStream.cs @@ -29,7 +29,7 @@ public override async Task WriteAsync(byte[] buffer, int offset, int count, Canc int headerSize = GetHeaderSize(buffer, offset); - ushort seq = (ushort)((buffer[offset + 2] << 8) | + ushort seq = (ushort)((buffer[offset + 2] << 8) | (buffer[offset + 3] << 0)); uint timestamp = (uint)((buffer[offset + 4] << 24) | @@ -46,7 +46,7 @@ public static bool TryReadSsrc(byte[] buffer, int offset, out uint ssrc) ssrc = 0; if (buffer.Length - offset < 12) return false; - + int version = (buffer[offset + 0] & 0b1100_0000) >> 6; if (version != 2) return false; @@ -71,8 +71,8 @@ public static int GetHeaderSize(byte[] buffer, int offset) return 12 + csics * 4; int extensionOffset = offset + 12 + (csics * 4); - int extensionLength = - (buffer[extensionOffset + 2] << 8) | + int extensionLength = + (buffer[extensionOffset + 2] << 8) | (buffer[extensionOffset + 3]); return extensionOffset + 4 + (extensionLength * 4); } @@ -83,4 +83,4 @@ protected override void Dispose(bool disposing) _next.Dispose(); base.Dispose(disposing); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Streams/RTPWriteStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/RTPWriteStream.cs index 6069d60b..2e2ede71 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/RTPWriteStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/RTPWriteStream.cs @@ -33,7 +33,7 @@ public override void WriteHeader(ushort seq, uint timestamp, bool missed) { if (_hasHeader) throw new InvalidOperationException("Header received with no payload"); - + _hasHeader = true; _nextSeq = seq; _nextTimestamp = timestamp; @@ -76,4 +76,4 @@ protected override void Dispose(bool disposing) _next.Dispose(); base.Dispose(disposing); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Streams/SodiumDecryptStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/SodiumDecryptStream.cs index 5a6f48bc..3fe12151 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/SodiumDecryptStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/SodiumDecryptStream.cs @@ -51,4 +51,4 @@ protected override void Dispose(bool disposing) _next.Dispose(); base.Dispose(disposing); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Audio/Streams/SodiumEncryptStream.cs b/src/Kook.Net.WebSocket/Audio/Streams/SodiumEncryptStream.cs index cdbdedb1..4609e76c 100644 --- a/src/Kook.Net.WebSocket/Audio/Streams/SodiumEncryptStream.cs +++ b/src/Kook.Net.WebSocket/Audio/Streams/SodiumEncryptStream.cs @@ -45,7 +45,7 @@ public override async Task WriteAsync(byte[] buffer, int offset, int count, Canc if (_client.SecretKey == null) return; - + Buffer.BlockCopy(buffer, offset, _nonce, 0, 12); //Copy nonce from RTP header count = SecretBox.Encrypt(buffer, offset + 12, count - 12, buffer, 12, _nonce, _client.SecretKey); _next.WriteHeader(_nextSeq, _nextTimestamp, false); @@ -67,4 +67,4 @@ protected override void Dispose(bool disposing) _next.Dispose(); base.Dispose(disposing); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/BaseSocketClient.Event.cs b/src/Kook.Net.WebSocket/BaseSocketClient.Event.cs index 8f19b003..13732e60 100644 --- a/src/Kook.Net.WebSocket/BaseSocketClient.Event.cs +++ b/src/Kook.Net.WebSocket/BaseSocketClient.Event.cs @@ -26,17 +26,17 @@ public event Func ChannelCreated } internal readonly AsyncEvent> _channelCreatedEvent = new AsyncEvent>(); /// Fired when a channel is destroyed. - /// - /// - /// This event is fired when a generic channel has been destroyed. The event handler must return a - /// and accept a as its parameter. - /// - /// - /// The destroyed channel is passed into the event handler parameter. The given channel type may - /// include, but not limited to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category); - /// see the derived classes of for more details. - /// - /// + /// + /// + /// This event is fired when a generic channel has been destroyed. The event handler must return a + /// and accept a as its parameter. + /// + /// + /// The destroyed channel is passed into the event handler parameter. The given channel type may + /// include, but not limited to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category); + /// see the derived classes of for more details. + /// + /// public event Func ChannelDestroyed { add => _channelDestroyedEvent.Add(value); @@ -142,7 +142,7 @@ public event Func, Cacheable, So internal readonly AsyncEvent, Cacheable, SocketReaction, Task>> _directReactionRemovedEvent = new AsyncEvent, Cacheable, SocketReaction, Task>>(); #endregion - + #region Messages /// Fired when a message is received. @@ -193,7 +193,7 @@ public event Func, Cacheable, remove => _messageDeletedEvent.Remove(value); } internal readonly AsyncEvent, Cacheable, Task>> _messageDeletedEvent = new AsyncEvent, Cacheable, Task>>(); - + /// Fired when a message is updated. /// /// @@ -252,7 +252,7 @@ public event Func, SocketMessage, ISocketMessageChanne remove => _messagePinnedEvent.Remove(value); } internal readonly AsyncEvent, SocketMessage, ISocketMessageChannel, SocketGuildUser, Task>> _messagePinnedEvent = new AsyncEvent, SocketMessage, ISocketMessageChannel, SocketGuildUser, Task>>(); - + /// Fired when a message is unpinned. /// /// @@ -284,7 +284,7 @@ public event Func, SocketMessage, ISocketMessageChanne } internal readonly AsyncEvent, SocketMessage, ISocketMessageChannel, SocketGuildUser, Task>> _messageUnpinnedEvent = new AsyncEvent, SocketMessage, ISocketMessageChannel, SocketGuildUser, Task>>(); - + #endregion #region Direct Messages @@ -337,7 +337,7 @@ public event Func, Cacheable, Task> remove => _directMessageDeletedEvent.Remove(value); } internal readonly AsyncEvent, Cacheable, Task>> _directMessageDeletedEvent = new AsyncEvent, Cacheable, Task>>(); - + /// Fired when a message is updated. /// /// @@ -373,7 +373,7 @@ public event Func, SocketMessage, IDMChannel, Task> Di internal readonly AsyncEvent, SocketMessage, IDMChannel, Task>> _directMessageUpdatedEvent = new AsyncEvent, SocketMessage, IDMChannel, Task>>(); #endregion - + #region Users /// Fired when a user joins a guild. @@ -394,7 +394,7 @@ public event Func UserLeft add => _userLeftEvent.Add(value); remove => _userLeftEvent.Remove(value); } - internal readonly AsyncEvent> _userLeftEvent = new AsyncEvent>(); + internal readonly AsyncEvent> _userLeftEvent = new AsyncEvent>(); /// Fired when a user is banned from a guild. /// /// @@ -491,7 +491,7 @@ public event Func, DateTimeOffset, Task> Gu remove => _guildMemberOfflineEvent.Remove(value); } internal readonly AsyncEvent, DateTimeOffset, Task>> _guildMemberOfflineEvent = new AsyncEvent, DateTimeOffset, Task>>(); - + #endregion #region Voices @@ -565,7 +565,7 @@ public event Func EmoteUpdated #endregion #region Guilds - + /// Fired when the connected account joins a guild. public event Func JoinedGuild { @@ -615,11 +615,12 @@ public event Func> _messageButtonClickedEvent = new AsyncEvent>(); /// Fired when a button is clicked in a direct card message. - public event Func DirectMessageButtonClicked { + public event Func DirectMessageButtonClicked + { add => _directMessageButtonClickedEvent.Add(value); remove => _directMessageButtonClickedEvent.Remove(value); } internal readonly AsyncEvent> _directMessageButtonClickedEvent = new AsyncEvent>(); #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/BaseSocketClient.cs b/src/Kook.Net.WebSocket/BaseSocketClient.cs index c61e8b4c..83124de9 100644 --- a/src/Kook.Net.WebSocket/BaseSocketClient.cs +++ b/src/Kook.Net.WebSocket/BaseSocketClient.cs @@ -104,4 +104,4 @@ internal BaseSocketClient(KookSocketConfig config, KookRestApiClient client) /// A generic WebSocket-based user; null when the user cannot be found. /// public abstract SocketUser GetUser(string username, string identifyNumber); -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/ClientState.cs b/src/Kook.Net.WebSocket/ClientState.cs index f0db9683..6ed88b4b 100644 --- a/src/Kook.Net.WebSocket/ClientState.cs +++ b/src/Kook.Net.WebSocket/ClientState.cs @@ -8,17 +8,17 @@ internal class ClientState private const double AverageChannelsPerGuild = 10.22; //Source: Googie2149 private const double AverageUsersPerGuild = 47.78; //Source: Googie2149 private const double CollectionMultiplier = 1.05; //Add 5% buffer to handle growth - + private readonly ConcurrentDictionary _guildChannels; private readonly ConcurrentDictionary _dmChannels; private readonly ConcurrentDictionary _guilds; private readonly ConcurrentDictionary _users; - + internal IReadOnlyCollection GuildChannels => _guildChannels.ToReadOnlyCollection(); internal IReadOnlyCollection DMChannels => _dmChannels.ToReadOnlyCollection(); internal IReadOnlyCollection Guilds => _guilds.ToReadOnlyCollection(); internal IReadOnlyCollection Users => _users.ToReadOnlyCollection(); - + public ClientState(int guildCount, int dmChannelCount) { double estimatedChannelCount = guildCount * AverageChannelsPerGuild + dmChannelCount; @@ -28,7 +28,7 @@ public ClientState(int guildCount, int dmChannelCount) _guilds = new ConcurrentDictionary(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(guildCount * CollectionMultiplier)); _users = new ConcurrentDictionary(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(estimatedUsersCount * CollectionMultiplier)); } - + internal SocketChannel GetChannel(ulong id) { if (_guildChannels.TryGetValue(id, out SocketChannel channel)) @@ -66,7 +66,7 @@ internal void PurgeDMChannels() { _dmChannels.Clear(); } - + internal SocketGuild GetGuild(ulong id) { if (_guilds.TryGetValue(id, out SocketGuild guild)) @@ -87,7 +87,7 @@ internal SocketGuild RemoveGuild(ulong id) } return null; } - + internal SocketGlobalUser GetUser(ulong id) { if (_users.TryGetValue(id, out SocketGlobalUser user)) @@ -109,5 +109,5 @@ internal void PurgeUsers() foreach (var guild in _guilds.Values) guild.PurgeUserCache(); } - -} \ No newline at end of file + +} diff --git a/src/Kook.Net.WebSocket/Commands/SocketCommandContext.cs b/src/Kook.Net.WebSocket/Commands/SocketCommandContext.cs index 5d2a326a..e71b5c0e 100644 --- a/src/Kook.Net.WebSocket/Commands/SocketCommandContext.cs +++ b/src/Kook.Net.WebSocket/Commands/SocketCommandContext.cs @@ -73,4 +73,4 @@ public SocketCommandContext(KookSocketClient client, SocketUserMessage msg) IUserMessage ICommandContext.Message => Message; #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/ConnectionManager.cs b/src/Kook.Net.WebSocket/ConnectionManager.cs index e3868ff5..294ba2f9 100644 --- a/src/Kook.Net.WebSocket/ConnectionManager.cs +++ b/src/Kook.Net.WebSocket/ConnectionManager.cs @@ -156,7 +156,8 @@ private async Task ConnectAsync(CancellationTokenSource reconnectCancelToken) } private async Task DisconnectAsync(Exception ex, bool isReconnecting) { - if (State == ConnectionState.Disconnected) return; + if (State == ConnectionState.Disconnected) + return; State = ConnectionState.Disconnecting; await _logger.InfoAsync("Disconnecting").ConfigureAwait(false); @@ -230,4 +231,4 @@ public void Dispose() { Dispose(true); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Channels/ISocketAudioChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/ISocketAudioChannel.cs index a2da51c8..a6a15cb8 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/ISocketAudioChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/ISocketAudioChannel.cs @@ -5,4 +5,4 @@ namespace Kook.WebSocket; /// public interface ISocketAudioChannel : IAudioChannel { -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Channels/ISocketMessageChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/ISocketMessageChannel.cs index d852bac9..4670f975 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/ISocketMessageChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/ISocketMessageChannel.cs @@ -34,7 +34,7 @@ public interface ISocketMessageChannel : IMessageChannel /// enabled. /// SocketMessage GetCachedMessage(Guid id); - + /// /// Gets the last N cached messages from this message channel. /// @@ -103,4 +103,4 @@ public interface ISocketMessageChannel : IMessageChannel /// A read-only collection of WebSocket-based messages. /// IReadOnlyCollection GetCachedMessages(IMessage fromMessage, Direction dir, int limit = KookConfig.MaxMessagesPerBatch); -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Channels/ISocketPrivateChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/ISocketPrivateChannel.cs index 77e3a798..f5924a9e 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/ISocketPrivateChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/ISocketPrivateChannel.cs @@ -14,4 +14,4 @@ public interface ISocketPrivateChannel : IPrivateChannel /// A read-only collection of users that can access this channel. /// new IReadOnlyCollection Recipients { get; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Channels/SocketCategoryChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/SocketCategoryChannel.cs index 92b01a5e..50fa783d 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/SocketCategoryChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/SocketCategoryChannel.cs @@ -1,6 +1,6 @@ +using Kook.Rest; using System.Collections.Immutable; using System.Diagnostics; -using Kook.Rest; using Model = Kook.API.Channel; namespace Kook.WebSocket; @@ -40,9 +40,9 @@ internal SocketCategoryChannel(KookSocketClient kook, ulong id, SocketGuild guil entity.Update(state, model); return entity; } - + #endregion - + #region Users /// public override SocketGuildUser GetUser(ulong id) @@ -59,10 +59,10 @@ public override SocketGuildUser GetUser(ulong id) } #endregion - + private string DebuggerDisplay => $"{Name} ({Id}, Category)"; internal new SocketCategoryChannel Clone() => MemberwiseClone() as SocketCategoryChannel; - + #region IGuildChannel /// @@ -82,9 +82,9 @@ async Task IGuildChannel.GetUserAsync(ulong id, CacheMode mode, Requ return await ChannelHelper.GetUserAsync(this, Guild, Kook, id, options).ConfigureAwait(false); } - + #endregion - + #region IChannel /// @@ -103,7 +103,7 @@ async Task IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions return await ChannelHelper.GetUserAsync(this, Guild, Kook, id, options).ConfigureAwait(false); } - + #endregion - -} \ No newline at end of file + +} diff --git a/src/Kook.Net.WebSocket/Entities/Channels/SocketChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/SocketChannel.cs index 6793ebf7..0175c4f9 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/SocketChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/SocketChannel.cs @@ -10,26 +10,26 @@ namespace Kook.WebSocket; public abstract class SocketChannel : SocketEntity, IChannel, IUpdateable { #region SocketChannel - + /// /// Gets a collection of users from the WebSocket cache. /// public IReadOnlyCollection Users => GetUsersInternal(); - - internal SocketChannel(KookSocketClient kook, ulong id) + + internal SocketChannel(KookSocketClient kook, ulong id) : base(kook, id) { } - + internal abstract void Update(ClientState state, Model model); - + /// public virtual Task UpdateAsync(RequestOptions options = null) => Task.Delay(0); - + #endregion #region User - + /// /// Gets a generic user from this channel. /// @@ -42,10 +42,10 @@ internal SocketChannel(KookSocketClient kook, ulong id) internal abstract IReadOnlyCollection GetUsersInternal(); #endregion - + private string DebuggerDisplay => $"Unknown ({Id}, Channel)"; internal SocketChannel Clone() => MemberwiseClone() as SocketChannel; - + #region IChannel /// @@ -58,4 +58,4 @@ IAsyncEnumerable> IChannel.GetUsersAsync(CacheMode mo => AsyncEnumerable.Empty>(); //Overridden #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Channels/SocketChannelHelper.cs b/src/Kook.Net.WebSocket/Entities/Channels/SocketChannelHelper.cs index 0629956f..5a5607ab 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/SocketChannelHelper.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/SocketChannelHelper.cs @@ -1,5 +1,5 @@ -using System.Collections.Immutable; using Kook.Rest; +using System.Collections.Immutable; namespace Kook.WebSocket; @@ -41,7 +41,7 @@ public static IAsyncEnumerable> GetMessagesAsync(I return result; //Download remaining messages - Guid? maxId = cachedMessages.Count > 0 + Guid? maxId = cachedMessages.Count > 0 #if NET6_0_OR_GREATER ? cachedMessages.MaxBy(x => x.Timestamp)?.Id #else @@ -63,7 +63,7 @@ public static IAsyncEnumerable> GetMessagesAsync(I return ChannelHelper.GetMessagesAsync(channel, kook, referenceMessageId, dir, limit, true, options); } } - + public static IReadOnlyCollection GetCachedMessages(ISocketMessageChannel channel, KookSocketClient kook, MessageCache messages, Guid? referenceMessageId, Direction dir, int limit) { @@ -78,11 +78,16 @@ public static void AddMessage(ISocketMessageChannel channel, KookSocketClient ko { switch (channel) { - case SocketDMChannel dmChannel: dmChannel.AddMessage(msg); break; - case SocketTextChannel textChannel: textChannel.AddMessage(msg); break; - default: throw new NotSupportedException($"Unexpected {nameof(ISocketMessageChannel)} type."); + case SocketDMChannel dmChannel: + dmChannel.AddMessage(msg); + break; + case SocketTextChannel textChannel: + textChannel.AddMessage(msg); + break; + default: + throw new NotSupportedException($"Unexpected {nameof(ISocketMessageChannel)} type."); } - } + } /// Unexpected type. public static SocketMessage RemoveMessage(ISocketMessageChannel channel, KookSocketClient kook, Guid id) @@ -94,13 +99,13 @@ public static SocketMessage RemoveMessage(ISocketMessageChannel channel, KookSoc _ => throw new NotSupportedException($"Unexpected {nameof(ISocketMessageChannel)} type."), }; } - + public static async Task UpdateAsync(SocketGuildChannel channel, RequestOptions options) { var model = await channel.Kook.ApiClient.GetGuildChannelAsync(channel.Id, options).ConfigureAwait(false); channel.Update(channel.Kook.State, model); } - + public static async Task UpdateAsync(SocketDMChannel channel, RequestOptions options) { var model = await channel.Kook.ApiClient.GetUserChatAsync(channel.Id, options).ConfigureAwait(false); @@ -113,4 +118,4 @@ public static async Task> GetConnectedUsers var users = await channel.Kook.ApiClient.GetConnectedUsersAsync(channel.Id, options).ConfigureAwait(false); return users.Select(x => SocketGuildUser.Create(guild, kook.State, x)).ToImmutableArray(); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Channels/SocketDMChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/SocketDMChannel.cs index f5457885..fe0c6ab6 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/SocketDMChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/SocketDMChannel.cs @@ -1,12 +1,12 @@ -using System.Collections.Immutable; -using System.Text.Encodings.Web; -using System.Text.Json; -using System.Text.Json.Serialization; using Kook.API; using Kook.API.Rest; using Kook.Net.Converters; using Kook.Rest; using Kook.Utils; +using System.Collections.Immutable; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; namespace Kook.WebSocket; @@ -24,7 +24,7 @@ public class SocketDMChannel : SocketChannel, IDMChannel, ISocketPrivateChannel, /// This property is the same as . /// public new Guid Id { get; } - + /// /// /// This property is the same as . @@ -35,7 +35,7 @@ public class SocketDMChannel : SocketChannel, IDMChannel, ISocketPrivateChannel, /// Gets the recipient of the channel. /// public SocketUser Recipient { get; } - + /// public IReadOnlyCollection CachedMessages => ImmutableArray.Create(); @@ -70,18 +70,18 @@ internal void Update(ClientState state, UserChat model) /// public override Task UpdateAsync(RequestOptions options = null) => SocketChannelHelper.UpdateAsync(this, options); - + /// public Task CloseAsync(RequestOptions options = null) => ChannelHelper.DeleteDMChannelAsync(this, Kook, options); - + #endregion #region Messages /// public SocketMessage GetCachedMessage(Guid id) => null; - + /// /// Gets the message associated with the given . /// @@ -94,7 +94,7 @@ public async Task GetMessageAsync(Guid id, RequestOptions options = nu { return await ChannelHelper.GetDirectMessageAsync(this, Kook, id, options).ConfigureAwait(false); } - + /// /// Gets the last N messages from this message channel. /// @@ -236,18 +236,18 @@ public Task> SendCardsAsync(IEnumerable car /// public Task> SendCardAsync(ICard card, IQuote quote = null, RequestOptions options = null) => ChannelHelper.SendDirectCardAsync(this, Kook, card, options, quote: quote); - + /// public async Task ModifyMessageAsync(Guid messageId, Action func, RequestOptions options = null) => await ChannelHelper.ModifyDirectMessageAsync(this, messageId, func, Kook, options).ConfigureAwait(false); - + /// public Task DeleteMessageAsync(Guid messageId, RequestOptions options = null) => ChannelHelper.DeleteDirectMessageAsync(this, messageId, Kook, options); /// public Task DeleteMessageAsync(IMessage message, RequestOptions options = null) => ChannelHelper.DeleteDirectMessageAsync(this, message.Id, Kook, options); - + internal void AddMessage(SocketMessage msg) { } @@ -255,7 +255,7 @@ internal SocketMessage RemoveMessage(Guid id) => null; #endregion - + #region Users /// @@ -284,17 +284,17 @@ internal override void Update(ClientState state, Channel model) { throw new NotSupportedException("Update a DMChannel via Channel is not supported"); } - + /// internal override IReadOnlyCollection GetUsersInternal() => Users; /// internal override SocketUser GetUserInternal(ulong id) => GetUser(id); - + #endregion - + #region IDMChannel - + /// IUser IDMChannel.Recipient => Recipient; #endregion @@ -307,36 +307,36 @@ internal override void Update(ClientState state, Channel model) #region IPrivateChannel /// IReadOnlyCollection IPrivateChannel.Recipients => ImmutableArray.Create(Recipient); - + #endregion - + #region IMessageChannel - + /// Task> IDMChannel.SendFileAsync(string path, string fileName, AttachmentType type, IQuote quote, RequestOptions options) - => SendFileAsync(path, fileName, type, (Quote) quote, options); + => SendFileAsync(path, fileName, type, (Quote)quote, options); /// Task> IDMChannel.SendFileAsync(Stream stream, string fileName, AttachmentType type, IQuote quote, RequestOptions options) - => SendFileAsync(stream, fileName, type, (Quote) quote, options); + => SendFileAsync(stream, fileName, type, (Quote)quote, options); /// Task> IDMChannel.SendFileAsync(FileAttachment attachment, IQuote quote, RequestOptions options) - => SendFileAsync(attachment, (Quote) quote, options); + => SendFileAsync(attachment, (Quote)quote, options); /// Task> IDMChannel.SendTextAsync(string text, IQuote quote, RequestOptions options) - => SendTextAsync(text, (Quote) quote, options); + => SendTextAsync(text, (Quote)quote, options); /// Task> IDMChannel.SendCardAsync(ICard card, IQuote quote, RequestOptions options) - => SendCardAsync(card, (Quote) quote, options); + => SendCardAsync(card, (Quote)quote, options); /// Task> IDMChannel.SendCardsAsync(IEnumerable cards, IQuote quote, RequestOptions options) - => SendCardsAsync(cards, (Quote) quote, options); - + => SendCardsAsync(cards, (Quote)quote, options); + /// async Task IMessageChannel.GetMessageAsync(Guid id, CacheMode mode, RequestOptions options) { @@ -354,9 +354,9 @@ IAsyncEnumerable> IMessageChannel.GetMessagesAsync /// IAsyncEnumerable> IMessageChannel.GetMessagesAsync(IMessage referenceMessage, Direction dir, int limit, CacheMode mode, RequestOptions options) => mode == CacheMode.CacheOnly ? null : GetMessagesAsync(referenceMessage.Id, dir, limit, options); - + /// - Task> IMessageChannel.SendFileAsync(string path, string fileName, + Task> IMessageChannel.SendFileAsync(string path, string fileName, AttachmentType type, IQuote quote, IUser ephemeralUser, RequestOptions options) => SendFileAsync(path, fileName, type, quote, options); /// @@ -364,7 +364,7 @@ Task> IMessageChannel.SendFileAsync(Stream stream, AttachmentType type, IQuote quote, IUser ephemeralUser, RequestOptions options) => SendFileAsync(stream, fileName, type, quote, options); /// - Task> IMessageChannel.SendFileAsync(FileAttachment attachment, + Task> IMessageChannel.SendFileAsync(FileAttachment attachment, IQuote quote, IUser ephemeralUser, RequestOptions options) => SendFileAsync(attachment, quote, options); /// @@ -380,9 +380,9 @@ Task> IMessageChannel.SendCardAsync(ICard card, IQuote quote, IUser ephemeralUser, RequestOptions options) => SendCardAsync(card, quote, options); #endregion - + #region IChannel - + /// string IChannel.Name => $"@{Recipient}"; @@ -392,13 +392,13 @@ Task IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions optio /// IAsyncEnumerable> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options) => ImmutableArray.Create>(Users).ToAsyncEnumerable(); - + #endregion - + /// /// Returns the recipient user. /// public override string ToString() => $"@{Recipient}"; private string DebuggerDisplay => $"@{Recipient} ({Id}, DM)"; internal new SocketDMChannel Clone() => MemberwiseClone() as SocketDMChannel; -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs index a6e70c89..45e9dd8c 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs @@ -1,6 +1,6 @@ +using Kook.Rest; using System.Collections.Immutable; using System.Diagnostics; -using Kook.Rest; using Model = Kook.API.Channel; namespace Kook.WebSocket; @@ -67,7 +67,7 @@ internal static SocketGuildChannel Create(SocketGuild guild, ClientState state, _ => new SocketGuildChannel(guild.Kook, model.Id, guild), }; } - + /// internal override void Update(ClientState state, Model model) { @@ -80,7 +80,7 @@ internal override void Update(ClientState state, Model model) for (int i = 0; i < rolePermissionOverwrites.Length; i++) newRoleOverwrites.Add(rolePermissionOverwrites[i].ToEntity()); _rolePermissionOverwrites = newRoleOverwrites.ToImmutable(); - + var userPermissionOverwrites = model.UserPermissionOverwrites; var newUserOverwrites = ImmutableArray.CreateBuilder(userPermissionOverwrites.Length); for (int i = 0; i < userPermissionOverwrites.Length; i++) @@ -91,14 +91,14 @@ internal override void Update(ClientState state, Model model) /// public override Task UpdateAsync(RequestOptions options = null) => SocketChannelHelper.UpdateAsync(this, options); - + /// public Task ModifyAsync(Action func, RequestOptions options = null) => ChannelHelper.ModifyAsync(this, Kook, func, options); /// public Task DeleteAsync(RequestOptions options = null) => ChannelHelper.DeleteGuildChannelAsync(this, Kook, options); - + /// /// Gets the permission overwrite for a specific user. /// @@ -182,7 +182,7 @@ public async Task RemovePermissionOverwriteAsync(IRole role, RequestOptions opti { await ChannelHelper.RemovePermissionOverwriteAsync(this, Kook, role, options).ConfigureAwait(false); } - + /// /// Updates the permission overwrite for the given user, if one exists. /// @@ -196,7 +196,7 @@ public async Task ModifyPermissionOverwriteAsync(IGuildUser user, Func /// Updates the permission overwrite for the given role, if one exists. /// @@ -211,7 +211,7 @@ public async Task ModifyPermissionOverwriteAsync(IRole role, Func null; - + /// /// Gets the name of the channel. /// @@ -221,25 +221,25 @@ public async Task ModifyPermissionOverwriteAsync(IRole role, Func Name; private string DebuggerDisplay => $"{Name} ({Id}, Guild)"; internal new SocketGuildChannel Clone() => MemberwiseClone() as SocketGuildChannel; - + #endregion - + #region SocketChannel - + /// internal override SocketUser GetUserInternal(ulong id) => GetUser(id); /// internal override IReadOnlyCollection GetUsersInternal() => Users; - + #endregion - + #region IGuildChannel - + /// IGuild IGuildChannel.Guild => Guild; /// ulong IGuildChannel.GuildId => Guild.Id; - + /// async Task IGuildChannel.AddPermissionOverwriteAsync(IRole role, RequestOptions options) => await AddPermissionOverwriteAsync(role, options).ConfigureAwait(false); @@ -258,14 +258,14 @@ async Task IGuildChannel.ModifyPermissionOverwriteAsync(IRole role, Func async Task IGuildChannel.ModifyPermissionOverwriteAsync(IGuildUser user, Func func, RequestOptions options) => await ModifyPermissionOverwriteAsync(user, func, options).ConfigureAwait(false); - + /// IAsyncEnumerable> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options) => ImmutableArray.Create>(Users).ToAsyncEnumerable(); //Overridden in Text/Voice /// Task IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult(GetUser(id)); //Overridden in Text/Voice - + /// /// Gets the creator of this channel. /// @@ -279,17 +279,17 @@ Task IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOpt /// Task IGuildChannel.GetCreatorAsync(CacheMode mode, RequestOptions options) => Task.FromResult(Creator); - + #endregion #region IChannel - + /// IAsyncEnumerable> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options) => ImmutableArray.Create>(Users).ToAsyncEnumerable(); //Overridden in Text/Voice /// Task IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult(GetUser(id)); //Overridden in Text/Voice - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Channels/SocketTextChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/SocketTextChannel.cs index df11140b..1095f475 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/SocketTextChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/SocketTextChannel.cs @@ -1,15 +1,14 @@ -using System.Collections.Immutable; -using Model = Kook.API.Channel; - -using System.Diagnostics; -using System.Text.Encodings.Web; -using System.Text.Json; -using System.Text.Json.Serialization; using Kook.API; using Kook.API.Rest; using Kook.Net.Converters; using Kook.Rest; using Kook.Utils; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using Model = Kook.API.Channel; namespace Kook.WebSocket; @@ -22,7 +21,7 @@ public class SocketTextChannel : SocketGuildChannel, ITextChannel, ISocketMessag #region SocketTextChannel private readonly MessageCache _messages; - + /// public string Topic { get; set; } /// @@ -45,7 +44,7 @@ public ICategoryChannel Category public string PlainTextMention => MentionUtils.PlainTextMentionChannel(Id); public IReadOnlyCollection CachedMessages => _messages?.Messages ?? ImmutableArray.Create(); - + /// public override IReadOnlyCollection Users => Guild.Users.Where(x => Permissions.GetValue( @@ -73,18 +72,18 @@ internal override void Update(ClientState state, Model model) SlowModeInterval = model.SlowMode / 1000; IsPermissionSynced = model.PermissionSync; } - + /// public virtual Task ModifyAsync(Action func, RequestOptions options = null) => ChannelHelper.ModifyAsync(this, Kook, func, options); - + private string DebuggerDisplay => $"{Name} ({Id}, Text)"; internal new SocketTextChannel Clone() => MemberwiseClone() as SocketTextChannel; #endregion #region Messages - + /// public SocketMessage GetCachedMessage(Guid id) => _messages?.Get(id); @@ -189,19 +188,19 @@ public Task> SendCardAsync(ICard card, Quote quote /// public async Task ModifyMessageAsync(Guid messageId, Action func, RequestOptions options = null) => await ChannelHelper.ModifyMessageAsync(this, messageId, func, Kook, options).ConfigureAwait(false); - + /// public Task DeleteMessageAsync(Guid messageId, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, messageId, Kook, options); /// public Task DeleteMessageAsync(IMessage message, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, message.Id, Kook, options); - + internal void AddMessage(SocketMessage msg) => _messages?.Add(msg); internal SocketMessage RemoveMessage(Guid id) => _messages?.Remove(id); - + #endregion #region Invites @@ -233,9 +232,9 @@ public override SocketGuildUser GetUser(ulong id) return null; } #endregion - + #region IGuildChannel - + /// async Task IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) { @@ -260,28 +259,28 @@ IAsyncEnumerable> IGuildChannel.GetUsersAsync(Ca /// Task> IMessageChannel.SendFileAsync(string path, string fileName, AttachmentType type, IQuote quote, IUser ephemeralUser, RequestOptions options) - => SendFileAsync(path, fileName, type, (Quote) quote, ephemeralUser, options); + => SendFileAsync(path, fileName, type, (Quote)quote, ephemeralUser, options); /// Task> IMessageChannel.SendFileAsync(Stream stream, string fileName, AttachmentType type, IQuote quote, IUser ephemeralUser, RequestOptions options) - => SendFileAsync(stream, fileName, type, (Quote) quote, ephemeralUser, options); + => SendFileAsync(stream, fileName, type, (Quote)quote, ephemeralUser, options); /// Task> IMessageChannel.SendFileAsync(FileAttachment attachment, IQuote quote, IUser ephemeralUser, RequestOptions options) - => SendFileAsync(attachment, (Quote) quote, ephemeralUser, options); + => SendFileAsync(attachment, (Quote)quote, ephemeralUser, options); /// Task> IMessageChannel.SendTextAsync(string text, IQuote quote, IUser ephemeralUser, RequestOptions options) - => SendTextAsync(text, (Quote) quote, ephemeralUser, options); + => SendTextAsync(text, (Quote)quote, ephemeralUser, options); /// Task> IMessageChannel.SendCardAsync(ICard card, IQuote quote, IUser ephemeralUser, RequestOptions options) - => SendCardAsync(card, (Quote) quote, ephemeralUser, options); + => SendCardAsync(card, (Quote)quote, ephemeralUser, options); /// Task> IMessageChannel.SendCardsAsync(IEnumerable cards, IQuote quote, IUser ephemeralUser, RequestOptions options) - => SendCardsAsync(cards, (Quote) quote, ephemeralUser, options); - + => SendCardsAsync(cards, (Quote)quote, ephemeralUser, options); + /// async Task IMessageChannel.GetMessageAsync(Guid id, CacheMode mode, RequestOptions options) { @@ -303,12 +302,12 @@ IAsyncEnumerable> IMessageChannel.GetMessagesAsync async Task> ITextChannel.GetPinnedMessagesAsync(RequestOptions options) => await GetPinnedMessagesAsync(options).ConfigureAwait(false); #endregion - + #region INestedChannel - + /// Task INestedChannel.GetCategoryAsync(CacheMode mode, RequestOptions options) => Task.FromResult(Category); - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs b/src/Kook.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs index a76ecc5e..b8393ff9 100644 --- a/src/Kook.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs +++ b/src/Kook.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs @@ -1,6 +1,6 @@ +using Kook.Rest; using System.Collections.Immutable; using System.Diagnostics; -using Kook.Rest; using Model = Kook.API.Channel; namespace Kook.WebSocket; @@ -62,8 +62,8 @@ public override IReadOnlyCollection Users /// public IReadOnlyCollection ConnectedUsers => Guild.Users.Where(x => x.VoiceChannel?.Id == Id).ToImmutableArray(); - - internal SocketVoiceChannel(KookSocketClient kook, ulong id, SocketGuild guild) + + internal SocketVoiceChannel(KookSocketClient kook, ulong id, SocketGuild guild) : base(kook, id, guild) { Type = ChannelType.Voice; @@ -85,7 +85,7 @@ internal override void Update(ClientState state, Model model) IsPermissionSynced = model.PermissionSync; HasPassword = model.HasPassword; } - + /// public override SocketGuildUser GetUser(ulong id) { @@ -106,9 +106,9 @@ public async Task> GetConnectedUsersAsync(C else return ConnectedUsers; } - + #endregion - + #region Invites /// @@ -124,18 +124,18 @@ public async Task CreateInviteAsync(InviteMaxAge maxAge = InviteMaxAge. #endregion #region IVoiceChannel - + /// async Task> IVoiceChannel.GetConnectedUsersAsync(CacheMode mode, RequestOptions options) => await GetConnectedUsersAsync(mode, options).ConfigureAwait(false); #endregion - + private string DebuggerDisplay => $"{Name} ({Id}, Voice)"; internal new SocketVoiceChannel Clone() => MemberwiseClone() as SocketVoiceChannel; - + #region IGuildChannel - + /// Task IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult(GetUser(id)); @@ -149,12 +149,12 @@ IAsyncEnumerable> IGuildChannel.GetUsersAsync(Ca } #endregion - + #region INestedChannel - + /// Task INestedChannel.GetCategoryAsync(CacheMode mode, RequestOptions options) => Task.FromResult(Category); #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Guilds/SocketGuild.cs b/src/Kook.Net.WebSocket/Entities/Guilds/SocketGuild.cs index d14841ca..096ceb73 100644 --- a/src/Kook.Net.WebSocket/Entities/Guilds/SocketGuild.cs +++ b/src/Kook.Net.WebSocket/Entities/Guilds/SocketGuild.cs @@ -1,15 +1,15 @@ +using Kook.API.Gateway; +using Kook.Rest; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics; -using Kook.API.Gateway; -using Kook.Rest; -using Model = Kook.API.Guild; +using BoostSubscription = Kook.API.Rest.BoostSubscription; using ChannelModel = Kook.API.Channel; -using MemberModel = Kook.API.Rest.GuildMember; using ExtendedModel = Kook.API.Rest.ExtendedGuild; -using RichModel = Kook.API.Rest.RichGuild; -using BoostSubscription = Kook.API.Rest.BoostSubscription; +using MemberModel = Kook.API.Rest.GuildMember; +using Model = Kook.API.Guild; using RecommendInfo = Kook.Rest.RecommendInfo; +using RichModel = Kook.API.Rest.RichGuild; using RoleModel = Kook.API.Role; using UserModel = Kook.API.User; @@ -82,7 +82,7 @@ public class SocketGuild : SocketEntity, IGuild, IDisposable, IUpdateable public string AutoDeleteTime { get; private set; } /// public RecommendInfo RecommendInfo { get; private set; } - + /// /// Gets the number of members. /// @@ -108,7 +108,7 @@ public class SocketGuild : SocketEntity, IGuild, IDisposable, IUpdateable public int? MemberCount { get; internal set; } /// Gets the number of members downloaded to the local guild cache. public int DownloadedMemberCount { get; private set; } - + internal bool IsAvailable { get; private set; } /// Indicates whether the client is connected to this guild. public bool IsConnected { get; internal set; } @@ -135,7 +135,7 @@ public class SocketGuild : SocketEntity, IGuild, IDisposable, IUpdateable /// A role object that represents an @everyone role in this guild. /// public SocketRole EveryoneRole => GetRole(0); - + /// /// Gets a collection of all text channels in this guild. /// @@ -166,7 +166,7 @@ public IReadOnlyCollection VoiceChannels /// public IReadOnlyCollection CategoryChannels => Channels.OfType().ToImmutableArray(); - + /// /// Gets a collection of all channels in this guild. /// @@ -304,7 +304,7 @@ public IReadOnlyCollection Channels /// /// public IReadOnlyCollection Roles => _roles.ToReadOnlyCollection(); - + internal SocketGuild(KookSocketClient kook, ulong id) : base(kook, id) { } internal static SocketGuild Create(KookSocketClient client, ClientState state, Model model) { @@ -322,7 +322,7 @@ internal static SocketGuild Create(KookSocketClient client, ClientState state, R internal void Update(ClientState state, IReadOnlyCollection models) { var channels = new ConcurrentDictionary(ConcurrentHashSet.DefaultConcurrencyLevel, - (int) (models.Count * 1.05)); + (int)(models.Count * 1.05)); foreach (ChannelModel model in models) { var channel = SocketGuildChannel.Create(this, state, model); @@ -341,7 +341,7 @@ internal void Update(ClientState state, IReadOnlyCollection models) if (members.TryAdd(member.Id, member)) member.GlobalUser.AddRef(); } - + DownloadedMemberCount = members.Count; _members = members; MemberCount = members.Count; @@ -358,7 +358,7 @@ internal void Update(ClientState state, RichModel model) { Update(state, model as ExtendedModel); OwnerId = model.OwnerId; // override - + if (model.Emojis != null) { _emotes.Clear(); @@ -394,7 +394,7 @@ internal void Update(ClientState state, Model model) IsAvailable = true; var roles = new ConcurrentDictionary(ConcurrentHashSet.DefaultConcurrencyLevel, - (int) ((model.Roles?.Length ?? 0) * 1.05)); + (int)((model.Roles?.Length ?? 0) * 1.05)); { for (int i = 0; i < (model.Roles?.Length ?? 0); i++) { @@ -407,7 +407,7 @@ internal void Update(ClientState state, Model model) int channelCount = model.Channels?.Length ?? 0; channelCount += (model.Channels ?? Array.Empty()).Sum(x => x.Channels?.Length ?? 0); var channels = new ConcurrentDictionary(ConcurrentHashSet.DefaultConcurrencyLevel, - (int) (channelCount * 1.05)); + (int)(channelCount * 1.05)); { for (int i = 0; i < (model.Channels?.Length ?? 0); i++) { @@ -445,13 +445,13 @@ internal void Update(ClientState state, GuildEvent model) IsAvailable = true; } - + /// public Task UpdateAsync(RequestOptions options = null) => SocketGuildHelper.UpdateAsync(this, Kook, options); - + #endregion - + /// /// Gets the name of the guild. /// @@ -475,7 +475,7 @@ public Task SocketGuildHelper.GetActiveBoostSubscriptionsAsync(this, Kook, options); #endregion - + #region Bans /// public Task> GetBansAsync(RequestOptions options = null) @@ -627,7 +627,7 @@ internal void PurgeChannelCache(ClientState state) // => GuildHelper.GetInvitesAsync(this, Kook, options); // // #endregion - + #region Roles /// @@ -656,7 +656,7 @@ public SocketRole GetRole(uint id) /// public Task CreateRoleAsync(string name, RequestOptions options = null) => GuildHelper.CreateRoleAsync(this, Kook, name, options); - + internal SocketRole AddRole(RoleModel model) { var role = SocketRole.Create(this, Kook.State, model); @@ -678,9 +678,9 @@ internal SocketRole AddOrUpdateRole(RoleModel model) return role; } - + #endregion - + #region Users /// @@ -758,7 +758,7 @@ public void PurgeUserCache(Func predicate) var membersToKeep = Users.Where(x => !predicate.Invoke(x) || x?.Id == Kook.CurrentUser.Id); foreach (var member in membersToPurge) - if(_members.TryRemove(member.Id, out _)) + if (_members.TryRemove(member.Id, out _)) member.GlobalUser.RemoveRef(Kook); foreach (var member in membersToKeep) @@ -817,20 +817,20 @@ public async Task DownloadBoostSubscriptionsAsync(RequestOptions options = null) /// users that matches the properties with the provided /// at . /// - public IAsyncEnumerable> SearchUsersAsync(Action func, + public IAsyncEnumerable> SearchUsersAsync(Action func, int limit = KookConfig.MaxUsersPerBatch, RequestOptions options = null) => GuildHelper.SearchUsersAsync(this, Kook, func, limit, options); - + #endregion #region Voices - + /// public async Task MoveUsersAsync(IEnumerable users, IVoiceChannel targetChannel, RequestOptions options) => await ClientHelper.MoveUsersAsync(Kook, users, targetChannel, options).ConfigureAwait(false); #endregion - + #region Emotes /// @@ -875,7 +875,7 @@ public Task> GetEmotesAsync(RequestOptions optio public Task GetEmoteAsync(string id, RequestOptions options = null) => GuildHelper.GetEmoteAsync(this, Kook, id, options); /// - public Task CreateEmoteAsync(string name, Image image , RequestOptions options = null) + public Task CreateEmoteAsync(string name, Image image, RequestOptions options = null) => GuildHelper.CreateEmoteAsync(this, Kook, name, image, options); /// /// is . @@ -886,9 +886,9 @@ public Task DeleteEmoteAsync(GuildEmote emote, RequestOptions options = null) => GuildHelper.DeleteEmoteAsync(this, Kook, emote.Id, options); #endregion - + #region Invites - + /// public async Task> GetInvitesAsync(RequestOptions options = null) => await GuildHelper.GetInvitesAsync(this, Kook, options).ConfigureAwait(false); @@ -900,7 +900,7 @@ public async Task CreateInviteAsync(InviteMaxAge maxAge = InviteMaxAge. => await GuildHelper.CreateInviteAsync(this, Kook, maxAge, maxUses, options).ConfigureAwait(false); #endregion - + #region Voice States internal SocketVoiceState AddOrUpdateVoiceState(ulong userId, ulong? voiceChannelId) @@ -911,7 +911,7 @@ internal SocketVoiceState AddOrUpdateVoiceState(ulong userId, ulong? voiceChanne var socketState = GetVoiceState(userId) ?? SocketVoiceState.Default; socketState.Update(voiceChannel); _voiceStates[userId] = socketState; - return socketState; + return socketState; } internal SocketVoiceState AddOrUpdateVoiceState(ulong userId, bool? isMuted = null, bool? isDeafened = null) @@ -938,12 +938,12 @@ internal SocketVoiceState AddOrUpdateVoiceState(ulong userId, bool? isMuted = nu #endregion #region IGuild - + /// bool IGuild.Available => true; - + public void Dispose() { } - + /// async Task> IGuild.GetUsersAsync(CacheMode mode, RequestOptions options) { @@ -982,7 +982,7 @@ IAsyncEnumerable> IGuild.SearchUsersAsync(Action /// async Task IGuild.CreateRoleAsync(string name, RequestOptions options) => await CreateRoleAsync(name, options).ConfigureAwait(false); - + /// async Task> IGuild.GetBansAsync(RequestOptions options) => await GetBansAsync(options).ConfigureAwait(false); @@ -992,7 +992,7 @@ async Task IGuild.GetBanAsync(IUser user, RequestOptions options) /// async Task IGuild.GetBanAsync(ulong userId, RequestOptions options) => await GetBanAsync(userId, options).ConfigureAwait(false); - + /// Task> IGuild.GetChannelsAsync(CacheMode mode, RequestOptions options) => Task.FromResult>(Channels); @@ -1021,7 +1021,7 @@ Task IGuild.GetVoiceChannelAsync(ulong id, CacheMode mode, Reques Task> IGuild.GetCategoryChannelsAsync(CacheMode mode, RequestOptions options) => Task.FromResult>(CategoryChannels); - + /// async Task IGuild.CreateTextChannelAsync(string name, Action func, RequestOptions options) => await CreateTextChannelAsync(name, func, options).ConfigureAwait(false); @@ -1039,4 +1039,4 @@ public async Task GetBadgeAsync(BadgeStyle style = BadgeStyle.GuildName, } #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Guilds/SocketGuildHelper.cs b/src/Kook.Net.WebSocket/Entities/Guilds/SocketGuildHelper.cs index 2bc0b943..f2b683fe 100644 --- a/src/Kook.Net.WebSocket/Entities/Guilds/SocketGuildHelper.cs +++ b/src/Kook.Net.WebSocket/Entities/Guilds/SocketGuildHelper.cs @@ -1,6 +1,6 @@ -using System.Collections.Immutable; using Kook.API.Rest; using Kook.Rest; +using System.Collections.Immutable; namespace Kook.WebSocket; @@ -41,4 +41,4 @@ public static async Task); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Invites/SocketInvite.cs b/src/Kook.Net.WebSocket/Entities/Invites/SocketInvite.cs index 9ca935c3..d26f1fb4 100644 --- a/src/Kook.Net.WebSocket/Entities/Invites/SocketInvite.cs +++ b/src/Kook.Net.WebSocket/Entities/Invites/SocketInvite.cs @@ -1,5 +1,5 @@ -using System.Diagnostics; using Kook.Rest; +using System.Diagnostics; using Model = Kook.API.Invite; namespace Kook.WebSocket; @@ -50,7 +50,7 @@ public class SocketInvite : SocketEntity, IInvite /// Gets the user that created this invite if available. /// public SocketGuildUser Inviter { get; private set; } - + /// public string Code { get; private set; } /// @@ -74,7 +74,7 @@ internal void Update(Model model) Code = model.UrlCode; Url = model.Url; GuildId = model.GuildId; - ChannelId = model.ChannelId ; + ChannelId = model.ChannelId; ExpiresAt = model.ExpiresAt; MaxAge = model.Duration; MaxUses = model.UsingTimes == -1 ? null : model.UsingTimes; @@ -119,4 +119,4 @@ ChannelType IInvite.ChannelType string IInvite.ChannelName => Channel.Name; /// string IInvite.GuildName => Guild.Name; -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Messages/MessageCache.cs b/src/Kook.Net.WebSocket/Entities/Messages/MessageCache.cs index 4d6da593..64e0cb8a 100644 --- a/src/Kook.Net.WebSocket/Entities/Messages/MessageCache.cs +++ b/src/Kook.Net.WebSocket/Entities/Messages/MessageCache.cs @@ -41,15 +41,17 @@ public SocketMessage Get(Guid id) return result; return null; } - + /// is less than 0. public IReadOnlyCollection GetMany(Guid? referenceMessageId, Direction dir, int limit = KookConfig.MaxMessagesPerBatch) { - if (limit < 0) throw new ArgumentOutOfRangeException(nameof(limit)); - if (limit == 0) return ImmutableArray.Empty; + if (limit < 0) + throw new ArgumentOutOfRangeException(nameof(limit)); + if (limit == 0) + return ImmutableArray.Empty; SocketMessage referenceMessage = _messages.SingleOrDefault(x => x.Key == referenceMessageId).Value; - + IEnumerable cachedMessageIds; if (referenceMessageId == null || dir == Direction.Unspecified) cachedMessageIds = _orderedMessages.Select(x => x.MsgId); @@ -84,4 +86,4 @@ public IReadOnlyCollection GetMany(Guid? referenceMessageId, Dire .Take(limit) .ToImmutableArray(); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Messages/SocketMessage.cs b/src/Kook.Net.WebSocket/Entities/Messages/SocketMessage.cs index 8441a5be..d6c9f88a 100644 --- a/src/Kook.Net.WebSocket/Entities/Messages/SocketMessage.cs +++ b/src/Kook.Net.WebSocket/Entities/Messages/SocketMessage.cs @@ -1,7 +1,7 @@ -using System.Collections.Immutable; using Kook.API; using Kook.API.Gateway; using Kook.Rest; +using System.Collections.Immutable; namespace Kook.WebSocket; @@ -83,7 +83,7 @@ public abstract class SocketMessage : SocketEntity, IMessage, IUpdateable /// Collection of poke action objects. /// public virtual IReadOnlyCollection Pokes => ImmutableArray.Create(); - + /// /// Returns the roles mentioned in this message. /// @@ -97,7 +97,7 @@ public abstract class SocketMessage : SocketEntity, IMessage, IUpdateable /// /// Collection of WebSocket-based users. /// - public IReadOnlyCollection MentionedUsers => _userMentions; + public IReadOnlyCollection MentionedUsers => _userMentions; /// public virtual IReadOnlyCollection Tags => ImmutableArray.Create(); /// @@ -122,7 +122,7 @@ internal virtual void Update(ClientState state, GatewayGroupMessageExtraData mod Type = gatewayEvent.Type; Timestamp = gatewayEvent.MessageTimestamp; Content = gatewayEvent.Content; - + if (model.MentionedUsers is not null) { var ids = model.MentionedUsers; @@ -176,7 +176,7 @@ internal virtual void Update(ClientState state, API.Message model) Timestamp = model.CreateAt; EditedTimestamp = model.UpdateAt; Content = model.Content; - + if (model.MentionedUsers is not null) { var ids = model.MentionedUsers; @@ -204,7 +204,7 @@ internal virtual void Update(ClientState state, MessageUpdateEvent model) { EditedTimestamp = model.UpdatedAt; Content = model.Content; - + if (model.Mention is not null) { var ids = model.Mention; @@ -229,8 +229,8 @@ internal virtual void Update(ClientState state, DirectMessageUpdateEvent model) /// public Task DeleteAsync(RequestOptions options = null) => MessageHelper.DeleteAsync(this, Kook, options); - - + + internal void AddReaction(SocketReaction reaction) { _reactions.Add(reaction); @@ -252,7 +252,7 @@ internal void RemoveReactionsForEmote(IEmote emote) /// public Task UpdateAsync(RequestOptions options = null) => SocketMessageHelper.UpdateAsync(this, Kook, options); - + /// public Task AddReactionAsync(IEmote emote, RequestOptions options = null) { @@ -307,7 +307,7 @@ public Task> GetReactionUsersAsync(IEmote emote, Requ /// public override string ToString() => Content; internal SocketMessage Clone() => MemberwiseClone() as SocketMessage; - + #region IMessage /// @@ -327,4 +327,4 @@ public Task> GetReactionUsersAsync(IEmote emote, Requ /// IReadOnlyCollection IMessage.Pokes => Pokes; #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Messages/SocketMessageHelper.cs b/src/Kook.Net.WebSocket/Entities/Messages/SocketMessageHelper.cs index b2345f88..a5aa91a2 100644 --- a/src/Kook.Net.WebSocket/Entities/Messages/SocketMessageHelper.cs +++ b/src/Kook.Net.WebSocket/Entities/Messages/SocketMessageHelper.cs @@ -52,4 +52,4 @@ public static async Task UpdateAsync(SocketMessage msg, KookSocketClient client, throw new InvalidOperationException("Cannot reload a message from a non-SocketTextChannel or non-SocketTextChannel."); } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Messages/SocketPokeAction.cs b/src/Kook.Net.WebSocket/Entities/Messages/SocketPokeAction.cs index 19eb45e7..e30c8824 100644 --- a/src/Kook.Net.WebSocket/Entities/Messages/SocketPokeAction.cs +++ b/src/Kook.Net.WebSocket/Entities/Messages/SocketPokeAction.cs @@ -6,7 +6,7 @@ public class SocketPokeAction : IPokeAction { /// public SocketUser Operator { get; } - + /// public IReadOnlyCollection Targets { get; } @@ -35,4 +35,4 @@ internal static SocketPokeAction Create(KookSocketClient kook, SocketUser @opera /// IPoke IPokeAction.Poke => Poke; #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Messages/SocketReaction.cs b/src/Kook.Net.WebSocket/Entities/Messages/SocketReaction.cs index e60affef..06572f91 100644 --- a/src/Kook.Net.WebSocket/Entities/Messages/SocketReaction.cs +++ b/src/Kook.Net.WebSocket/Entities/Messages/SocketReaction.cs @@ -56,7 +56,7 @@ public class SocketReaction : IReaction public ISocketMessageChannel Channel { get; } /// public IEmote Emote { get; } - + internal SocketReaction(ISocketMessageChannel channel, Guid messageId, SocketUserMessage message, ulong userId, IUser user, IEmote emoji) { Channel = channel; @@ -84,4 +84,4 @@ internal static SocketReaction Create(API.Gateway.PrivateReaction model, IDMChan emote = new Emote(model.Emoji.Id, model.Emoji.Name); return new SocketReaction(channel as ISocketMessageChannel, model.MessageId, message, model.UserId, user, emote); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Messages/SocketSystemMessage.cs b/src/Kook.Net.WebSocket/Entities/Messages/SocketSystemMessage.cs index 4c9f198c..7f254e06 100644 --- a/src/Kook.Net.WebSocket/Entities/Messages/SocketSystemMessage.cs +++ b/src/Kook.Net.WebSocket/Entities/Messages/SocketSystemMessage.cs @@ -1,5 +1,5 @@ -using System.Diagnostics; using Kook.API.Gateway; +using System.Diagnostics; namespace Kook.WebSocket; @@ -11,7 +11,7 @@ public class SocketSystemMessage : SocketMessage, ISystemMessage { /// public SystemMessageType SystemMessageType { get; private set; } - + internal SocketSystemMessage(KookSocketClient kook, Guid id, ISocketMessageChannel channel, SocketUser author) : base(kook, id, channel, author, MessageSource.System) { @@ -60,7 +60,7 @@ internal override void Update(ClientState state, MessageUpdateEvent model) base.Update(state, model); // TODO: SystemMessageType } - + private string DebuggerDisplay => $"{Author}: {Content} ({Id}, {Type})"; internal new SocketSystemMessage Clone() => MemberwiseClone() as SocketSystemMessage; -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Messages/SocketUserMessage.cs b/src/Kook.Net.WebSocket/Entities/Messages/SocketUserMessage.cs index d1f00eef..8ee33360 100644 --- a/src/Kook.Net.WebSocket/Entities/Messages/SocketUserMessage.cs +++ b/src/Kook.Net.WebSocket/Entities/Messages/SocketUserMessage.cs @@ -1,13 +1,13 @@ +using Kook.API; +using Kook.API.Gateway; +using Kook.Net.Converters; +using Kook.Rest; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; -using Kook.API; -using Kook.API.Gateway; -using Kook.Net.Converters; -using Kook.Rest; namespace Kook.WebSocket; @@ -60,7 +60,7 @@ public class SocketUserMessage : SocketMessage, IUserMessage public override bool? MentionedHere => _isMentioningHere; /// public override IReadOnlyCollection Tags => _tags; - + internal SocketUserMessage(KookSocketClient kook, Guid id, ISocketMessageChannel channel, SocketUser author, MessageSource source) : base(kook, id, channel, author, source) { @@ -104,7 +104,7 @@ internal override void Update(ClientState state, GatewayGroupMessageExtraData mo else if (Type == MessageType.KMarkdown) _tags = MessageHelper.ParseTags(gatewayEvent.Content, Channel, guild, MentionedUsers, TagMode.KMarkdown); if (model.Quote is not null) - _quote = Quote.Create(model.Quote.Id, model.Quote.QuotedMessageId, model.Quote.Type, model.Quote.Content, + _quote = Quote.Create(model.Quote.Id, model.Quote.QuotedMessageId, model.Quote.Type, model.Quote.Content, model.Quote.CreateAt, guild.GetUser(model.Quote.Author.Id)); if (model.Attachment is not null) @@ -121,7 +121,7 @@ internal override void Update(ClientState state, GatewayGroupMessageExtraData mo Guild = guild; } - + internal override void Update(ClientState state, GatewayPersonMessageExtraData model, GatewayEvent gatewayEvent) { base.Update(state, model, gatewayEvent); @@ -147,14 +147,14 @@ internal override void Update(ClientState state, GatewayPersonMessageExtraData m : recipient.Id == Author.Id ? Kook.CurrentUser : recipient; - _pokes = model.KMarkdownInfo.Pokes.Select(x => SocketPokeAction.Create(Kook, Author, - new []{target}, x)).ToImmutableArray(); + _pokes = model.KMarkdownInfo.Pokes.Select(x => SocketPokeAction.Create(Kook, Author, + new[] { target }, x)).ToImmutableArray(); } else _pokes = ImmutableArray.Empty; } - + internal override void Update(ClientState state, API.Message model) { base.Update(state, model); @@ -168,7 +168,7 @@ internal override void Update(ClientState state, API.Message model) _tags = MessageHelper.ParseTags(model.Content, Channel, Guild, MentionedUsers, TagMode.PlainText); else if (Type == MessageType.KMarkdown) _tags = MessageHelper.ParseTags(model.Content, Channel, Guild, MentionedUsers, TagMode.KMarkdown); - + if (model.Attachment is not null) _attachments = _attachments.Add(Attachment.Create(model.Attachment)); @@ -183,7 +183,7 @@ internal override void Update(ClientState state, API.Message model) model.MentionedUsers.Select(state.GetUser), x)).ToImmutableArray() : ImmutableArray.Empty; - Guild = guild; + Guild = guild; } internal override void Update(ClientState state, API.DirectMessage model) { @@ -194,7 +194,7 @@ internal override void Update(ClientState state, API.DirectMessage model) _tags = MessageHelper.ParseTags(model.Content, Channel, Guild, MentionedUsers, TagMode.PlainText); else if (Type == MessageType.KMarkdown) _tags = MessageHelper.ParseTags(model.Content, Channel, Guild, MentionedUsers, TagMode.KMarkdown); - + if (model.Attachment is not null) _attachments = _attachments.Add(Attachment.Create(model.Attachment)); @@ -212,8 +212,8 @@ internal override void Update(ClientState state, API.DirectMessage model) : recipient.Id == Author.Id ? Kook.CurrentUser : recipient; - _pokes = model.MentionInfo.Pokes.Select(x => SocketPokeAction.Create(Kook, Author, - new []{target}, x)).ToImmutableArray(); + _pokes = model.MentionInfo.Pokes.Select(x => SocketPokeAction.Create(Kook, Author, + new[] { target }, x)).ToImmutableArray(); } else _pokes = ImmutableArray.Empty; @@ -233,11 +233,11 @@ internal override void Update(ClientState state, MessageUpdateEvent model) _tags = MessageHelper.ParseTags(model.Content, Channel, Guild, MentionedUsers, TagMode.PlainText); else if (Type == MessageType.KMarkdown) _tags = MessageHelper.ParseTags(model.Content, Channel, Guild, MentionedUsers, TagMode.KMarkdown); - - _cards = Type == MessageType.Card - ? MessageHelper.ParseCards(model.Content) + + _cards = Type == MessageType.Card + ? MessageHelper.ParseCards(model.Content) : ImmutableArray.Create(); - + Guild = guild; } internal override void Update(ClientState state, DirectMessageUpdateEvent model) @@ -249,20 +249,20 @@ internal override void Update(ClientState state, DirectMessageUpdateEvent model) _tags = MessageHelper.ParseTags(model.Content, Channel, Guild, MentionedUsers, TagMode.PlainText); else if (Type == MessageType.KMarkdown) _tags = MessageHelper.ParseTags(model.Content, Channel, Guild, MentionedUsers, TagMode.KMarkdown); - - _cards = Type == MessageType.Card - ? MessageHelper.ParseCards(model.Content) + + _cards = Type == MessageType.Card + ? MessageHelper.ParseCards(model.Content) : ImmutableArray.Create(); Guild = guild; } - + /// /// Only the author of a message may modify the message. /// Message content is too long, length must be less or equal to . public Task ModifyAsync(Action func, RequestOptions options = null) => MessageHelper.ModifyAsync(this, Kook, func, options); - + /// The zero-based index at which to begin the resolving for the specified value. /// public string Resolve(int startIndex, TagHandling userHandling = TagHandling.Name, TagHandling channelHandling = TagHandling.Name, @@ -272,7 +272,7 @@ public string Resolve(int startIndex, TagHandling userHandling = TagHandling.Nam public string Resolve(TagHandling userHandling = TagHandling.Name, TagHandling channelHandling = TagHandling.Name, TagHandling roleHandling = TagHandling.Name, TagHandling everyoneHandling = TagHandling.Ignore, TagHandling emojiHandling = TagHandling.Name) => MentionUtils.Resolve(this, 0, userHandling, channelHandling, roleHandling, everyoneHandling, emojiHandling); - + private string DebuggerDisplay => $"{Author}: {Content} ({Id}{(Attachments is not null && Attachments.Any() ? $", {Attachments.Count} Attachment{(Attachments.Count == 1 ? string.Empty : "s")}" : string.Empty)})"; internal new SocketUserMessage Clone() => MemberwiseClone() as SocketUserMessage; @@ -288,4 +288,4 @@ public string Resolve(TagHandling userHandling = TagHandling.Name, TagHandling c IReadOnlyCollection IMessage.Embeds => Embeds; #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Roles/SocketRole.cs b/src/Kook.Net.WebSocket/Entities/Roles/SocketRole.cs index 74a06825..580a10ee 100644 --- a/src/Kook.Net.WebSocket/Entities/Roles/SocketRole.cs +++ b/src/Kook.Net.WebSocket/Entities/Roles/SocketRole.cs @@ -1,9 +1,8 @@ -using System.Collections.Immutable; -using Model = Kook.API.Role; - -using System.Diagnostics; using Kook.API.Rest; using Kook.Rest; +using System.Collections.Immutable; +using System.Diagnostics; +using Model = Kook.API.Role; namespace Kook.WebSocket; /// @@ -21,7 +20,7 @@ public class SocketRole : SocketEntity, IRole /// A representing the parent guild of this role. /// public SocketGuild Guild { get; } - + /// public RoleType? Type { get; set; } /// @@ -68,26 +67,26 @@ internal void Update(ClientState state, Model model) Position = model.Position; IsHoisted = model.Hoist switch { - 0 => false, - 1 => true, + 0 => false, + 1 => true, _ => throw new ArgumentOutOfRangeException(nameof(model.Hoist)) }; IsMentionable = model.Mentionable switch { - 0 => false, - 1 => true, + 0 => false, + 1 => true, _ => throw new ArgumentOutOfRangeException(nameof(model.Mentionable)) }; Permissions = new GuildPermissions(model.Permissions); } - + /// public Task ModifyAsync(Action func, RequestOptions options = null) => RoleHelper.ModifyAsync(this, Kook, func, options); /// public Task DeleteAsync(RequestOptions options = null) => RoleHelper.DeleteAsync(this, Kook, options); - + /// /// Gets a collection of users with this role. /// @@ -128,12 +127,12 @@ public async IAsyncEnumerable> GetUsersAsyn await foreach (IReadOnlyCollection restUsers in restUserCollections) yield return restUsers.Select(restUser => Guild.AddOrUpdateUser(restUser)).ToList(); } - + /// public int CompareTo(IRole role) => RoleUtils.Compare(this, role); - + #endregion - + /// /// Gets the name of the role. /// @@ -143,12 +142,12 @@ public async IAsyncEnumerable> GetUsersAsyn public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Id})"; internal SocketRole Clone() => MemberwiseClone() as SocketRole; - + #region IRole - + /// IGuild IRole.Guild => Guild; - + /// IAsyncEnumerable> IRole.GetUsersAsync(CacheMode mode, RequestOptions options) { @@ -157,6 +156,6 @@ IAsyncEnumerable> IRole.GetUsersAsync(CacheMode else return AsyncEnumerable.Empty>(); } - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/SocketEntity.cs b/src/Kook.Net.WebSocket/Entities/SocketEntity.cs index 4cc09785..14736dee 100644 --- a/src/Kook.Net.WebSocket/Entities/SocketEntity.cs +++ b/src/Kook.Net.WebSocket/Entities/SocketEntity.cs @@ -4,7 +4,7 @@ public abstract class SocketEntity : IEntity where T : IEquatable { internal KookSocketClient Kook { get; } - + /// public T Id { get; } @@ -13,4 +13,4 @@ internal SocketEntity(KookSocketClient kook, T id) Kook = kook; Id = id; } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Users/SocketGlobalUser.cs b/src/Kook.Net.WebSocket/Entities/Users/SocketGlobalUser.cs index 3a8d2fea..4313b489 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/SocketGlobalUser.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/SocketGlobalUser.cs @@ -33,8 +33,8 @@ internal class SocketGlobalUser : SocketUser private readonly object _lockObj = new object(); private ushort _references; - - public SocketGlobalUser(KookSocketClient kook, ulong id) + + public SocketGlobalUser(KookSocketClient kook, ulong id) : base(kook, id) { } @@ -45,7 +45,7 @@ internal static SocketGlobalUser Create(KookSocketClient kook, ClientState state entity.UpdatePresence(model.Online, model.OperatingSystem); return entity; } - + internal void AddRef() { checked @@ -62,7 +62,7 @@ internal void RemoveRef(KookSocketClient kook) kook.RemoveUser(Id); } } - + private string DebuggerDisplay => $"{Username}#{IdentifyNumber} ({Id}{(IsBot ?? false ? ", Bot" : "")}, Global)"; internal new SocketGlobalUser Clone() => MemberwiseClone() as SocketGlobalUser; -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Users/SocketGuildUser.cs b/src/Kook.Net.WebSocket/Entities/Users/SocketGuildUser.cs index 842af943..60699d4d 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/SocketGuildUser.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/SocketGuildUser.cs @@ -1,9 +1,9 @@ -using System.Collections.Immutable; -using System.Diagnostics; using Kook.API.Gateway; using Kook.Rest; -using UserModel = Kook.API.User; +using System.Collections.Immutable; +using System.Diagnostics; using MemberModel = Kook.API.Rest.GuildMember; +using UserModel = Kook.API.User; namespace Kook.WebSocket; @@ -14,9 +14,9 @@ namespace Kook.WebSocket; public class SocketGuildUser : SocketUser, IGuildUser, IUpdateable { #region SocketGuildUser - + private ImmutableArray _roleIds; - + internal override SocketGlobalUser GlobalUser { get; } /// /// Gets the guild the user is in. @@ -28,7 +28,7 @@ public class SocketGuildUser : SocketUser, IGuildUser, IUpdateable public string Nickname { get; private set; } /// public bool IsMobileVerified { get; private set; } - + /// public DateTimeOffset JoinedAt { get; private set; } /// @@ -37,10 +37,10 @@ public class SocketGuildUser : SocketUser, IGuildUser, IUpdateable public Color Color { get; private set; } /// public bool? IsOwner { get; private set; } - + /// public new string PlainTextMention => MentionUtils.PlainTextMentionUser(Nickname ?? Username, Id); - + /// public override bool? IsBot { get => GlobalUser.IsBot; internal set => GlobalUser.IsBot = value; } /// @@ -61,12 +61,12 @@ public class SocketGuildUser : SocketUser, IGuildUser, IUpdateable public override bool? IsDenoiseEnabled { get => GlobalUser.IsDenoiseEnabled; internal set => GlobalUser.IsDenoiseEnabled = value; } /// public override UserTag UserTag { get => GlobalUser.UserTag; internal set => GlobalUser.UserTag = value; } - + /// public GuildPermissions GuildPermissions => new GuildPermissions(Permissions.ResolveGuild(Guild, this)); /// internal override SocketPresence Presence { get; set; } - + /// public bool? IsDeafened => VoiceState?.IsDeafened ?? false; /// @@ -113,7 +113,7 @@ public class SocketGuildUser : SocketUser, IGuildUser, IUpdateable /// public IReadOnlyCollection Roles => _roleIds.Select(id => Guild.GetRole(id)).Where(x => x != null).ToReadOnlyCollection(() => _roleIds.Length); - + /// /// Returns the voice channel the user is in, or null if none or unknown. /// @@ -133,7 +133,7 @@ public IReadOnlyCollection Roles /// connected to a voice channel nor is muted or deafened by the guild. /// public SocketVoiceState? VoiceState => Guild.GetVoiceState(Id); - + internal SocketGuildUser(SocketGuild guild, SocketGlobalUser globalUser) : base(guild.Kook, globalUser.Id) { @@ -193,7 +193,7 @@ private void UpdateRoles(uint[] roleIds) roles.Add(roleIds[i]); _roleIds = roles.ToImmutable(); } - + /// public Task ModifyNicknameAsync(string name, RequestOptions options = null) => UserHelper.ModifyNicknameAsync(this, Kook, name, options); @@ -268,16 +268,16 @@ public Task RemoveRolesAsync(IEnumerable roleIds, RequestOptions options = public Task RemoveRolesAsync(IEnumerable roles, RequestOptions options = null) => RemoveRolesAsync(roles.Select(x => x.Id)); /// - public Task MuteAsync(RequestOptions options = null) + public Task MuteAsync(RequestOptions options = null) => GuildHelper.MuteUserAsync(this, Kook, options); /// - public Task DeafenAsync(RequestOptions options = null) + public Task DeafenAsync(RequestOptions options = null) => GuildHelper.DeafenUserAsync(this, Kook, options); /// - public Task UnmuteAsync(RequestOptions options = null) + public Task UnmuteAsync(RequestOptions options = null) => GuildHelper.UnmuteUserAsync(this, Kook, options); /// - public Task UndeafenAsync(RequestOptions options = null) + public Task UndeafenAsync(RequestOptions options = null) => GuildHelper.UndeafenUserAsync(this, Kook, options); /// public async Task> GetConnectedVoiceChannelsAsync(RequestOptions options = null) @@ -320,12 +320,12 @@ async Task> IGuildUser.GetConnectedVoiceChann #endregion #region IVoiceState - + /// IVoiceChannel IVoiceState.VoiceChannel => VoiceChannel; #endregion - + private string DebuggerDisplay => $"{Username}#{IdentifyNumber} ({Id}{(IsBot ?? false ? ", Bot" : "")}, Guild)"; internal new SocketGuildUser Clone() => MemberwiseClone() as SocketGuildUser; -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Users/SocketPresence.cs b/src/Kook.Net.WebSocket/Entities/Users/SocketPresence.cs index b276e7f2..e0822bba 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/SocketPresence.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/SocketPresence.cs @@ -58,8 +58,8 @@ internal void Update(bool? isOnline, string activeClient) return type; return null; } - - private string DebuggerDisplay => $"{IsOnline switch {true => "Online", false => "Offline", _ => "Unknown Status"}}{ActiveClient.ToString()}"; + + private string DebuggerDisplay => $"{IsOnline switch { true => "Online", false => "Offline", _ => "Unknown Status" }}{ActiveClient.ToString()}"; internal SocketPresence Clone() => MemberwiseClone() as SocketPresence; -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Users/SocketSelfUser.cs b/src/Kook.Net.WebSocket/Entities/Users/SocketSelfUser.cs index 5ecc7c4e..372aaaba 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/SocketSelfUser.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/SocketSelfUser.cs @@ -1,8 +1,7 @@ -using Model = Kook.API.Rest.SelfUser; - +using Kook.Rest; using System.Diagnostics; using System.Globalization; -using Kook.Rest; +using Model = Kook.API.Rest.SelfUser; namespace Kook.WebSocket; @@ -13,7 +12,7 @@ namespace Kook.WebSocket; public class SocketSelfUser : SocketUser, ISelfUser { internal override SocketGlobalUser GlobalUser { get; } - + /// public override bool? IsBot { get => GlobalUser.IsBot; internal set => GlobalUser.IsBot = value; } /// @@ -35,7 +34,9 @@ public class SocketSelfUser : SocketUser, ISelfUser /// public override UserTag UserTag { get => GlobalUser.UserTag; internal set => GlobalUser.UserTag = value; } /// - internal override SocketPresence Presence { get => GlobalUser.Presence; set => GlobalUser.Presence = value; + internal override SocketPresence Presence + { + get => GlobalUser.Presence; set => GlobalUser.Presence = value; } /// public string MobilePrefix { get; internal set; } @@ -85,12 +86,12 @@ internal bool Update(ClientState state, Model model) } return hasGlobalChanges; } - + private string DebuggerDisplay => $"{Username}#{IdentifyNumber} ({Id}{(IsBot ?? false ? ", Bot" : "")}, Self)"; internal new SocketSelfUser Clone() => MemberwiseClone() as SocketSelfUser; #region ISelfUser - + /// public async Task StartPlayingAsync(IGame game, RequestOptions options = null) => await UserHelper.StartPlayingAsync(this, Kook, game, options).ConfigureAwait(false); @@ -102,4 +103,4 @@ public async Task StopPlayingAsync(ActivityType type, RequestOptions options = n => await UserHelper.StopPlayingAsync(this, Kook, type, options).ConfigureAwait(false); #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Users/SocketUnknownUser.cs b/src/Kook.Net.WebSocket/Entities/Users/SocketUnknownUser.cs index 355c2986..da1803cf 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/SocketUnknownUser.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/SocketUnknownUser.cs @@ -48,7 +48,7 @@ internal static SocketUnknownUser Create(KookSocketClient kook, ClientState stat var entity = new SocketUnknownUser(kook, id); return entity; } - + private string DebuggerDisplay => $"{Username}#{IdentifyNumber} ({Id}{(IsBot ?? false ? ", Bot" : "")}, Unknown)"; internal new SocketUnknownUser Clone() => MemberwiseClone() as SocketUnknownUser; -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Users/SocketUser.cs b/src/Kook.Net.WebSocket/Entities/Users/SocketUser.cs index 5149baa7..318206e0 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/SocketUser.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/SocketUser.cs @@ -1,6 +1,6 @@ +using Kook.Rest; using System.Diagnostics; using System.Globalization; -using Kook.Rest; using Model = Kook.API.User; namespace Kook.WebSocket; @@ -33,20 +33,20 @@ public abstract class SocketUser : SocketEntity, IUser public abstract UserTag UserTag { get; internal set; } internal abstract SocketGlobalUser GlobalUser { get; } internal abstract SocketPresence Presence { get; set; } - + /// public string IdentifyNumber => IdentifyNumberValue?.ToString("D4"); /// public string KMarkdownMention => MentionUtils.KMarkdownMentionUser(Id); /// public string PlainTextMention => MentionUtils.PlainTextMentionUser(Username, Id); - + /// public bool? IsOnline => Presence.IsOnline; /// public ClientType? ActiveClient => Presence.ActiveClient; - - protected SocketUser(KookSocketClient kook, ulong id) + + protected SocketUser(KookSocketClient kook, ulong id) : base(kook, id) { } @@ -54,13 +54,13 @@ protected SocketUser(KookSocketClient kook, ulong id) internal virtual bool Update(ClientState state, API.Gateway.UserUpdateEvent model) { bool hasChanges = false; - + if (model.Username != Username) { Username = model.Username; hasChanges = true; } - + if (model.Avatar != Avatar) { Avatar = model.Avatar; @@ -127,7 +127,7 @@ internal virtual bool Update(ClientState state, Model model) UserTag = model.UserTag.ToEntity(); hasChanges = true; } - + return hasChanges; } @@ -141,7 +141,7 @@ internal virtual void UpdatePresence(bool? isOnline, string activeClient) Presence ??= new SocketPresence(); Presence.Update(isOnline, activeClient); } - + /// public async Task CreateDMChannelAsync(RequestOptions options = null) => await SocketUserHelper.CreateDMChannelAsync(this, Kook, options).ConfigureAwait(false); @@ -153,7 +153,7 @@ public Task GetIntimacyAsync(RequestOptions options = null) /// public async Task UpdateIntimacyAsync(Action func, RequestOptions options = null) => await UserHelper.UpdateIntimacyAsync(this, Kook, func, options).ConfigureAwait(false); - + /// /// Gets the full name of the user (e.g. Example#0001). /// @@ -163,15 +163,15 @@ public async Task UpdateIntimacyAsync(Action func, RequestOp public override string ToString() => Format.UsernameAndIdentifyNumber(this); private string DebuggerDisplay => $"{Format.UsernameAndIdentifyNumber(this)} ({Id}{(IsBot ?? false ? ", Bot" : "")})"; internal SocketUser Clone() => MemberwiseClone() as SocketUser; - + #region IUser - + /// async Task IUser.CreateDMChannelAsync(RequestOptions options) => await CreateDMChannelAsync(options).ConfigureAwait(false); /// async Task IUser.GetIntimacyAsync(RequestOptions options) => await GetIntimacyAsync(options).ConfigureAwait(false); - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Users/SocketUserHelper.cs b/src/Kook.Net.WebSocket/Entities/Users/SocketUserHelper.cs index 395b7376..752c9782 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/SocketUserHelper.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/SocketUserHelper.cs @@ -1,6 +1,6 @@ -using System.Collections.Immutable; using Kook.API; using Kook.API.Rest; +using System.Collections.Immutable; namespace Kook.WebSocket; @@ -21,6 +21,6 @@ public static async Task UpdateAsync(SocketGuildUser user, KookSocketClient clie public static async Task CreateDMChannelAsync(SocketUser user, KookSocketClient client, RequestOptions options) { UserChat userChat = await client.ApiClient.CreateUserChatAsync(user.Id, options).ConfigureAwait(false); - return SocketDMChannel.Create(client,client.State, userChat.Code, userChat.Recipient); + return SocketDMChannel.Create(client, client.State, userChat.Code, userChat.Recipient); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Entities/Users/SocketVoiceState.cs b/src/Kook.Net.WebSocket/Entities/Users/SocketVoiceState.cs index 68042339..42636ecf 100644 --- a/src/Kook.Net.WebSocket/Entities/Users/SocketVoiceState.cs +++ b/src/Kook.Net.WebSocket/Entities/Users/SocketVoiceState.cs @@ -53,4 +53,4 @@ internal void Update(bool? isMuted, bool? isDeafened) /// IVoiceChannel IVoiceState.VoiceChannel => VoiceChannel; -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Extensions/SocketEntityExtensions.cs b/src/Kook.Net.WebSocket/Extensions/SocketEntityExtensions.cs index 004c8332..c1cd2eb4 100644 --- a/src/Kook.Net.WebSocket/Extensions/SocketEntityExtensions.cs +++ b/src/Kook.Net.WebSocket/Extensions/SocketEntityExtensions.cs @@ -8,14 +8,14 @@ public static GuildEmote ToEntity(this API.Gateway.GuildEmojiEvent model, ulong model.Type == EmojiType.Animated, guildId, null); - + public static RolePermissionOverwrite ToEntity(this API.RolePermissionOverwrite model) { return new RolePermissionOverwrite(model.RoleId, new OverwritePermissions(model.Allow, model.Deny)); } - + public static UserPermissionOverwrite ToEntity(this API.UserPermissionOverwrite model, KookSocketClient kook, ClientState state) { return new UserPermissionOverwrite(SocketGlobalUser.Create(kook, state, model.User), new OverwritePermissions(model.Allow, model.Deny)); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/GatewayReconnectException.cs b/src/Kook.Net.WebSocket/GatewayReconnectException.cs index 5c180341..bc07f2a2 100644 --- a/src/Kook.Net.WebSocket/GatewayReconnectException.cs +++ b/src/Kook.Net.WebSocket/GatewayReconnectException.cs @@ -15,4 +15,4 @@ public class GatewayReconnectException : Exception public GatewayReconnectException(string message) : base(message) { } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/KookSocketApiClient.cs b/src/Kook.Net.WebSocket/KookSocketApiClient.cs index 3c7dad0d..64f79a18 100644 --- a/src/Kook.Net.WebSocket/KookSocketApiClient.cs +++ b/src/Kook.Net.WebSocket/KookSocketApiClient.cs @@ -36,7 +36,7 @@ public event Func Disconnected } private readonly AsyncEvent> _disconnectedEvent = new AsyncEvent>(); - + private readonly bool _isExplicitUrl; private CancellationTokenSource _connectCancelToken; private string _gatewayUrl; @@ -44,7 +44,7 @@ public event Func Disconnected private int _lastSeq; public ConnectionState ConnectionState { get; private set; } internal IWebSocketClient WebSocketClient { get; } - + public KookSocketApiClient(RestClientProvider restClientProvider, WebSocketProvider webSocketProvider, string userAgent, string acceptLanguage, string url = null, RetryMode defaultRetryMode = RetryMode.AlwaysRetry, JsonSerializerOptions serializerOptions = null, Func defaultRatelimitCallback = null) @@ -53,7 +53,7 @@ public KookSocketApiClient(RestClientProvider restClientProvider, WebSocketProvi _gatewayUrl = url; if (url != null) _isExplicitUrl = true; - + WebSocketClient = webSocketProvider(); WebSocketClient.TextMessage += OnTextMessage; WebSocketClient.BinaryMessage += OnBinaryMessage; @@ -75,8 +75,8 @@ private async Task OnBinaryMessage(byte[] data, int index, int count) #else using MemoryStream decompressed = new(); #endif - using MemoryStream compressed = data[0] == 0x78 - ? new MemoryStream(data, index + 2, count - 2) + using MemoryStream compressed = data[0] == 0x78 + ? new MemoryStream(data, index + 2, count - 2) : new MemoryStream(data, index, count); #if NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER await using DeflateStream decompressor = new(compressed, CompressionMode.Decompress); @@ -141,7 +141,7 @@ internal override async Task ConnectInternalAsync() throw new InvalidOperationException("The client must be logged in before connecting."); if (WebSocketClient == null) throw new NotSupportedException("This client is not configured with WebSocket support."); - + RequestQueue.ClearGatewayBuckets(); ConnectionState = ConnectionState.Connecting; @@ -173,7 +173,7 @@ internal override async Task ConnectInternalAsync() throw; } } - + public async Task DisconnectAsync(Exception ex = null) { await _stateLock.WaitAsync().ConfigureAwait(false); @@ -189,10 +189,12 @@ internal override async Task DisconnectInternalAsync(Exception ex = null) if (WebSocketClient == null) throw new NotSupportedException("This client is not configured with WebSocket support."); - if (ConnectionState == ConnectionState.Disconnected) return; + if (ConnectionState == ConnectionState.Disconnected) + return; ConnectionState = ConnectionState.Disconnecting; - - try { _connectCancelToken?.Cancel(false); } + + try + { _connectCancelToken?.Cancel(false); } catch { // ignored @@ -205,19 +207,19 @@ internal override async Task DisconnectInternalAsync(Exception ex = null) ConnectionState = ConnectionState.Disconnected; } - + public async Task SendHeartbeatAsync(int lastSeq, RequestOptions options = null) { options = RequestOptions.CreateOrClone(options); await SendGatewayAsync(GatewaySocketFrameType.Ping, sequence: lastSeq, options: options).ConfigureAwait(false); } - + public async Task SendResumeAsync(int lastSeq, RequestOptions options = null) { options = RequestOptions.CreateOrClone(options); await SendGatewayAsync(GatewaySocketFrameType.Resume, sequence: lastSeq, options: options).ConfigureAwait(false); } - + public Task SendGatewayAsync(GatewaySocketFrameType gatewaySocketFrameType, object payload = null, int? sequence = null, RequestOptions options = null) => SendGatewayInternalAsync(gatewaySocketFrameType, options, payload, sequence); private async Task SendGatewayInternalAsync(GatewaySocketFrameType gatewaySocketFrameType, RequestOptions options, object payload = null, int? sequence = null) @@ -226,15 +228,15 @@ private async Task SendGatewayInternalAsync(GatewaySocketFrameType gatewaySocket payload = new GatewaySocketFrame { Type = gatewaySocketFrameType, Payload = payload, Sequence = sequence }; byte[] bytes = Encoding.UTF8.GetBytes(SerializeJson(payload)); - + options.IsGatewayBucket = true; if (options.BucketId == null) options.BucketId = GatewayBucket.Get(GatewayBucketType.Unbucketed).Id; await RequestQueue.SendAsync(new WebSocketRequest(WebSocketClient, bytes, true, gatewaySocketFrameType == GatewaySocketFrameType.Ping, options)).ConfigureAwait(false); await _sentGatewayMessageEvent.InvokeAsync(gatewaySocketFrameType).ConfigureAwait(false); - + #if DEBUG_PACKETS Debug.WriteLine($"-> [{gatewaySocketFrameType}] : #{sequence} \n{JsonSerializer.Serialize(payload, new JsonSerializerOptions {WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping})}".TrimEnd('\n')); #endif } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/KookSocketClient.Events.cs b/src/Kook.Net.WebSocket/KookSocketClient.Events.cs index 3111a0c8..879e46f5 100644 --- a/src/Kook.Net.WebSocket/KookSocketClient.Events.cs +++ b/src/Kook.Net.WebSocket/KookSocketClient.Events.cs @@ -1,6 +1,6 @@ +using Kook.API; using System; using System.Threading.Tasks; -using Kook.API; namespace Kook.WebSocket; @@ -40,4 +40,4 @@ public event Func LatencyUpdated private readonly AsyncEvent> _latencyUpdatedEvent = new AsyncEvent>(); #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/KookSocketClient.cs b/src/Kook.Net.WebSocket/KookSocketClient.cs index 61717d2a..d9faeb61 100644 --- a/src/Kook.Net.WebSocket/KookSocketClient.cs +++ b/src/Kook.Net.WebSocket/KookSocketClient.cs @@ -1,10 +1,3 @@ -using System.Collections.Concurrent; -using System.Collections.Immutable; -using System.Net; -using System.Runtime.CompilerServices; -using System.Text.Encodings.Web; -using System.Text.Json; -using System.Text.Json.Serialization; using Kook.API; using Kook.API.Gateway; using Kook.API.Rest; @@ -13,6 +6,13 @@ using Kook.Net.Udp; using Kook.Net.WebSockets; using Kook.Rest; +using System.Collections.Concurrent; +using System.Collections.Immutable; +using System.Net; +using System.Runtime.CompilerServices; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; namespace Kook.WebSocket; @@ -69,7 +69,7 @@ public partial class KookSocketClient : BaseSocketClient, IKookClient /// public IReadOnlyCollection DMChannels => State.DMChannels.OfType().ToImmutableArray(); - + /// /// Initializes a new REST/WebSocket-based Kook client. /// @@ -110,7 +110,7 @@ private KookSocketClient(KookSocketConfig config, KookSocketApiClient client) ApiClient.SentGatewayMessage += async socketFrameType => await _gatewayLogger.DebugAsync($"Sent {socketFrameType}").ConfigureAwait(false); ApiClient.ReceivedGatewayEvent += ProcessMessageAsync; - + LeftGuild += async g => await _gatewayLogger.InfoAsync($"Left {g.Name}").ConfigureAwait(false); JoinedGuild += async g => await _gatewayLogger.InfoAsync($"Joined {g.Name}").ConfigureAwait(false); GuildAvailable += async g => await _gatewayLogger.VerboseAsync($"Connected to {g.Name}").ConfigureAwait(false); @@ -119,7 +119,7 @@ private KookSocketClient(KookSocketConfig config, KookSocketApiClient client) GuildAvailable += g => { - if (_guildDownloadTask?.IsCompleted == true + if (_guildDownloadTask?.IsCompleted == true && ConnectionState == ConnectionState.Connected) { if (AlwaysDownloadUsers && g.HasAllMembers is not true) @@ -134,7 +134,7 @@ private KookSocketClient(KookSocketConfig config, KookSocketApiClient client) } private static KookSocketApiClient CreateApiClient(KookSocketConfig config) - => new KookSocketApiClient(config.RestClientProvider, config.WebSocketProvider, KookRestConfig.UserAgent, + => new KookSocketApiClient(config.RestClientProvider, config.WebSocketProvider, KookRestConfig.UserAgent, config.AcceptLanguage, config.GatewayHost, defaultRatelimitCallback: config.DefaultRatelimitCallback); internal override void Dispose(bool disposing) @@ -199,9 +199,10 @@ private async Task OnDisconnectingAsync(Exception ex) await heartbeatTask.ConfigureAwait(false); _heartbeatTask = null; - while (_heartbeatTimes.TryDequeue(out _)) { } + while (_heartbeatTimes.TryDequeue(out _)) + { } _lastMessageTime = 0; - + //Raise virtual GUILD_UNAVAILABLEs await _gatewayLogger.DebugAsync("Raising virtual GuildUnavailables").ConfigureAwait(false); foreach (var guild in State.Guilds) @@ -210,7 +211,7 @@ private async Task OnDisconnectingAsync(Exception ex) await GuildUnavailableAsync(guild).ConfigureAwait(false); } } - + /// public override SocketGuild GetGuild(ulong id) => State.GetGuild(id); @@ -263,15 +264,15 @@ public async ValueTask> GetDMChannelsAsync(Reque /// the identifier; null if the user is not found. /// public async ValueTask GetUserAsync(ulong id, RequestOptions options = null) - => await ((IKookClient) this).GetUserAsync(id, CacheMode.AllowDownload, options).ConfigureAwait(false); - + => await ((IKookClient)this).GetUserAsync(id, CacheMode.AllowDownload, options).ConfigureAwait(false); + /// public override SocketUser GetUser(ulong id) => State.GetUser(id); /// public override SocketUser GetUser(string username, string identifyNumber) => State.Users.FirstOrDefault(x => x.IdentifyNumber == identifyNumber && x.Username == username); - + internal SocketGlobalUser GetOrCreateUser(ClientState state, Kook.API.User model) { return state.GetOrAddUser(model.Id, x => SocketGlobalUser.Create(this, state, model)); @@ -339,7 +340,7 @@ private async Task ProcessVoiceStateDownloadsAsync(IEnumerable guilds, R foreach (User user in users) socketGuild.AddOrUpdateVoiceState(user.Id, channelId); } - + GetGuildMuteDeafListResponse model = await ApiClient.GetGuildMutedDeafenedUsersAsync(socketGuild.Id).ConfigureAwait(false); foreach (ulong id in model.Muted.UserIds) socketGuild.AddOrUpdateVoiceState(id, isMuted: true); @@ -376,7 +377,7 @@ private async Task ProcessBoostSubscriptionsDownloadsAsync(IEnumerable g } #region ProcessMessageAsync - + private async Task ProcessMessageAsync(GatewaySocketFrameType gatewaySocketFrameType, int? sequence, object payload) { if (sequence != null) @@ -389,15 +390,15 @@ private async Task ProcessMessageAsync(GatewaySocketFrameType gatewaySocketFrame { case GatewaySocketFrameType.Event: GatewayEvent gatewayEvent = - ((JsonElement) payload).Deserialize(_serializerOptions); + ((JsonElement)payload).Deserialize(_serializerOptions); dynamic eventExtraData = gatewayEvent!.Type switch { - MessageType.System => ((JsonElement) gatewayEvent.ExtraData) + MessageType.System => ((JsonElement)gatewayEvent.ExtraData) .Deserialize(_serializerOptions), - _ when gatewayEvent.ChannelType == "GROUP" => ((JsonElement) gatewayEvent.ExtraData).Deserialize( + _ when gatewayEvent.ChannelType == "GROUP" => ((JsonElement)gatewayEvent.ExtraData).Deserialize( _serializerOptions), - _ when gatewayEvent.ChannelType == "PERSON" => ((JsonElement) gatewayEvent.ExtraData).Deserialize( + _ when gatewayEvent.ChannelType == "PERSON" => ((JsonElement)gatewayEvent.ExtraData).Deserialize( _serializerOptions), _ => throw new InvalidOperationException("Unknown event type") }; @@ -412,1052 +413,1053 @@ private async Task ProcessMessageAsync(GatewaySocketFrameType gatewaySocketFrame case MessageType.KMarkdown: case MessageType.Poke: case MessageType.Card: - { - await _gatewayLogger.DebugAsync($"Received Message ({gatewayEvent.Type}, {gatewayEvent.ChannelType})").ConfigureAwait(false); - if (gatewayEvent.ChannelType == "GROUP") - { - GatewayGroupMessageExtraData extraData = eventExtraData as GatewayGroupMessageExtraData; - - var channel = GetChannel(gatewayEvent.TargetId) as ISocketMessageChannel; - SocketGuild guild = (channel as SocketGuildChannel)?.Guild; - - SocketUser author; - if (guild != null) - author = guild.GetUser(extraData.Author.Id); - else - author = (channel as SocketChannel)?.GetUser(extraData.Author.Id); - if (author == null) - { - if (guild != null) - { - author = guild.AddOrUpdateUser(extraData.Author); - } - else - { - await UnknownChannelUserAsync(gatewayEvent.Type.ToString(), extraData.Author.Id, channel.Id).ConfigureAwait(false); - return; - } - } - - var msg = SocketMessage.Create(this, State, author, channel, extraData, gatewayEvent); - SocketChannelHelper.AddMessage(channel, this, msg); - await TimedInvokeAsync(_messageReceivedEvent, nameof(MessageReceived), msg).ConfigureAwait(false); - } - else if (gatewayEvent.ChannelType == "PERSON") { - GatewayPersonMessageExtraData extraData = eventExtraData as GatewayPersonMessageExtraData; - var channel = CreateDMChannel(extraData.Code, extraData.Author, State); - - SocketUser author = (channel as SocketChannel).GetUser(extraData.Author.Id); - if (author == null) + await _gatewayLogger.DebugAsync($"Received Message ({gatewayEvent.Type}, {gatewayEvent.ChannelType})").ConfigureAwait(false); + if (gatewayEvent.ChannelType == "GROUP") { - await UnknownChannelUserAsync(gatewayEvent.Type.ToString(), extraData.Author.Id, extraData.Code).ConfigureAwait(false); - return; - } - var msg = SocketMessage.Create(this, State, author, channel, extraData, gatewayEvent); - SocketChannelHelper.AddMessage(channel, this, msg); - await TimedInvokeAsync(_directMessageReceivedEvent, nameof(DirectMessageReceived), msg).ConfigureAwait(false); - } - - } - break; - - case MessageType.System: - { - GatewaySystemEventExtraData extraData = eventExtraData as GatewaySystemEventExtraData; - switch (gatewayEvent.ChannelType, extraData!.Type) - { - #region Channels + GatewayGroupMessageExtraData extraData = eventExtraData as GatewayGroupMessageExtraData; - // 频道内用户添加 reaction - case ("GROUP", "added_reaction"): - { - await _gatewayLogger.DebugAsync("Received Event (added_reaction)").ConfigureAwait(false); - - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var channel = GetChannel(data.ChannelId) as ISocketMessageChannel; - - var cachedMsg = channel?.GetCachedMessage(data.MessageId) as SocketUserMessage; - bool isMsgCached = cachedMsg is not null; - - IUser user = channel is not null - ? await channel.GetUserAsync(data.UserId, CacheMode.CacheOnly).ConfigureAwait(false) - : GetUser(data.UserId); - - var cacheableChannel = new Cacheable(channel, data.ChannelId, channel != null, async () => await GetChannelAsync(data.ChannelId).ConfigureAwait(false) as IMessageChannel); - var cacheableMsg = new Cacheable(cachedMsg, data.MessageId, isMsgCached, async () => - { - var channelObj = await cacheableChannel.GetOrDownloadAsync().ConfigureAwait(false); - return await channelObj.GetMessageAsync(data.MessageId).ConfigureAwait(false) as IUserMessage; - }); - - var reaction = SocketReaction.Create(data, channel, cachedMsg, user); - - cachedMsg?.AddReaction(reaction); - - await TimedInvokeAsync(_reactionAddedEvent, nameof(ReactionAdded), cacheableMsg, cacheableChannel, reaction).ConfigureAwait(false); - } - break; + var channel = GetChannel(gatewayEvent.TargetId) as ISocketMessageChannel; + SocketGuild guild = (channel as SocketGuildChannel)?.Guild; - // 频道内用户取消 reaction - case ("GROUP", "deleted_reaction"): - { - await _gatewayLogger.DebugAsync("Received Event (deleted_reaction)").ConfigureAwait(false); - - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var channel = GetChannel(data.ChannelId) as ISocketMessageChannel; - - var cachedMsg = channel?.GetCachedMessage(data.MessageId) as SocketUserMessage; - bool isMsgCached = cachedMsg is not null; - - IUser user = channel is not null - ? await channel.GetUserAsync(data.UserId, CacheMode.CacheOnly).ConfigureAwait(false) - : GetUser(data.UserId); - - var cacheableChannel = new Cacheable(channel, data.ChannelId, channel != null, async () => await GetChannelAsync(data.ChannelId).ConfigureAwait(false) as IMessageChannel); - var cacheableMsg = new Cacheable(cachedMsg, data.MessageId, isMsgCached, async () => - { - var channelObj = await cacheableChannel.GetOrDownloadAsync().ConfigureAwait(false); - return await channelObj.GetMessageAsync(data.MessageId).ConfigureAwait(false) as IUserMessage; - }); - var reaction = SocketReaction.Create(data, channel, cachedMsg, user); - - cachedMsg?.RemoveReaction(reaction); - - await TimedInvokeAsync(_reactionRemovedEvent, nameof(ReactionRemoved), cacheableMsg, cacheableChannel, reaction).ConfigureAwait(false); - } - break; - - // 频道消息更新 - case ("GROUP", "updated_message"): - { - await _gatewayLogger.DebugAsync("Received Event (updated_message)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var channel = GetChannel(data.ChannelId) as ISocketMessageChannel; - var guild = (channel as SocketGuildChannel)?.Guild; - - SocketMessage before = null, after = null; - SocketMessage cachedMsg = channel?.GetCachedMessage(data.MessageId); - bool isCached = cachedMsg != null; - if (isCached) - { - before = cachedMsg.Clone(); - cachedMsg.Update(State, data); - after = cachedMsg; - } + SocketUser author; + if (guild != null) + author = guild.GetUser(extraData.Author.Id); else + author = (channel as SocketChannel)?.GetUser(extraData.Author.Id); + if (author == null) { - Message msg = await ApiClient.GetMessageAsync(data.MessageId).ConfigureAwait(false); - - SocketUser author = guild.GetUser(msg.Author.Id) - ?? (SocketUser) new SocketUnknownUser(this, id: 0); - - if (channel == null) + if (guild != null) + { + author = guild.AddOrUpdateUser(extraData.Author); + } + else { - await UnknownChannelAsync(extraData.Type, data.ChannelId).ConfigureAwait(false); + await UnknownChannelUserAsync(gatewayEvent.Type.ToString(), extraData.Author.Id, channel.Id).ConfigureAwait(false); return; } - - after = SocketMessage.Create(this, State, author, channel, msg); } - var cacheableBefore = new Cacheable(before, data.MessageId, isCached, async () => await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false)); - await TimedInvokeAsync(_messageUpdatedEvent, nameof(MessageUpdated), cacheableBefore, after, channel).ConfigureAwait(false); - } - break; - - // 频道消息被删除 - case ("GROUP", "deleted_message"): - { - await _gatewayLogger.DebugAsync("Received Event (deleted_message)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var channel = GetChannel(data.ChannelId) as ISocketMessageChannel; - var guild = (channel as SocketGuildChannel)?.Guild; - - SocketMessage msg = null; - if (channel != null) - msg = SocketChannelHelper.RemoveMessage(channel, this, data.MessageId); - var cacheableMsg = new Cacheable(msg, data.MessageId, msg != null, () => Task.FromResult((IMessage)null)); - var cacheableChannel = new Cacheable(channel, data.ChannelId, channel != null, async () => await GetChannelAsync(data.ChannelId).ConfigureAwait(false) as IMessageChannel); - - await TimedInvokeAsync(_messageDeletedEvent, nameof(MessageDeleted), cacheableMsg, cacheableChannel).ConfigureAwait(false); - } - break; - - // 新增频道 - case ("GROUP", "added_channel"): - { - await _gatewayLogger.DebugAsync("Received Event (added_channel)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - SocketChannel channel = null; - var guild = State.GetGuild(data.GuildId); - if (guild != null) - { - channel = guild.AddChannel(State, data); - } - else - { - await UnknownGuildAsync(extraData.Type, data.GuildId).ConfigureAwait(false); - return; - } - if (channel != null) - await TimedInvokeAsync(_channelCreatedEvent, nameof(ChannelCreated), channel).ConfigureAwait(false); + var msg = SocketMessage.Create(this, State, author, channel, extraData, gatewayEvent); + SocketChannelHelper.AddMessage(channel, this, msg); + await TimedInvokeAsync(_messageReceivedEvent, nameof(MessageReceived), msg).ConfigureAwait(false); } - break; - - // 修改频道信息 - case ("GROUP", "updated_channel"): + else if (gatewayEvent.ChannelType == "PERSON") { - await _gatewayLogger.DebugAsync("Received Event (updated_channel)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var channel = State.GetChannel(data.Id); - if (channel != null) - { - var before = channel.Clone(); - channel.Update(State, data); + GatewayPersonMessageExtraData extraData = eventExtraData as GatewayPersonMessageExtraData; + var channel = CreateDMChannel(extraData.Code, extraData.Author, State); - var guild = (channel as SocketGuildChannel)?.Guild; - await TimedInvokeAsync(_channelUpdatedEvent, nameof(ChannelUpdated), before, channel).ConfigureAwait(false); - } - else + SocketUser author = (channel as SocketChannel).GetUser(extraData.Author.Id); + if (author == null) { - await UnknownChannelAsync(extraData.Type, data.Id).ConfigureAwait(false); + await UnknownChannelUserAsync(gatewayEvent.Type.ToString(), extraData.Author.Id, extraData.Code).ConfigureAwait(false); return; } + var msg = SocketMessage.Create(this, State, author, channel, extraData, gatewayEvent); + SocketChannelHelper.AddMessage(channel, this, msg); + await TimedInvokeAsync(_directMessageReceivedEvent, nameof(DirectMessageReceived), msg).ConfigureAwait(false); } - break; - - // 删除频道 - case ("GROUP", "deleted_channel"): - { - await _gatewayLogger.DebugAsync("Received Event (deleted_channel)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var channel = State.GetChannel(data.ChannelId); - - var guild = (channel as SocketGuildChannel)?.Guild; - if (guild != null) - { - channel = guild.RemoveChannel(State, data.ChannelId); - } - else - { - await UnknownGuildAsync(extraData.Type, guildId: 0).ConfigureAwait(false); - return; - } + } + break; - if (channel != null) - await TimedInvokeAsync(_channelDestroyedEvent, nameof(ChannelDestroyed), channel).ConfigureAwait(false); - else - { - await UnknownChannelAsync(extraData.Type, data.ChannelId, guild?.Id ?? 0).ConfigureAwait(false); - return; - } - } - break; - - // 新的频道置顶消息 - case ("GROUP", "pinned_message"): - { - await _gatewayLogger.DebugAsync("Received Event (pinned_message)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var channel = GetChannel(data.ChannelId) as ISocketMessageChannel; - - if (channel == null) - { - await UnknownChannelAsync(extraData.Type, data.ChannelId).ConfigureAwait(false); - return; - } - - var guild = (channel as SocketGuildChannel)?.Guild; - if (guild != null) - { - SocketGuildUser operatorUser = guild.GetUser(data.OperatorUserId); - if (operatorUser == null) - { - GuildMember model = await ApiClient.GetGuildMemberAsync(guild.Id, data.OperatorUserId).ConfigureAwait(false); - operatorUser = guild.AddOrUpdateUser(model); - } - - Cacheable cacheableBefore; - SocketMessage after; - - SocketUserMessage cachedMsg = channel.GetCachedMessage(data.MessageId) as SocketUserMessage; - bool isCached = cachedMsg != null; - if (isCached) - { - SocketMessage before = cachedMsg.Clone(); - cachedMsg.IsPinned = true; - after = cachedMsg; - - cacheableBefore = new Cacheable(before, data.MessageId, true, async () => await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false)); - - } - else - { - Message msg = await ApiClient.GetMessageAsync(data.MessageId).ConfigureAwait(false); - SocketUser author = guild.GetUser(msg.Author.Id) - ?? (SocketUser) new SocketUnknownUser(this, id: 0); - after = SocketMessage.Create(this, State, author, channel, msg); - - cacheableBefore = new Cacheable(null, data.MessageId, false, async () => await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false)); - } - await TimedInvokeAsync(_messagePinnedEvent, nameof(MessagePinned), cacheableBefore, after, channel, operatorUser).ConfigureAwait(false); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; - - // 取消频道置顶消息 - case ("GROUP", "unpinned_message"): + case MessageType.System: + { + GatewaySystemEventExtraData extraData = eventExtraData as GatewaySystemEventExtraData; + switch (gatewayEvent.ChannelType, extraData!.Type) { - await _gatewayLogger.DebugAsync("Received Event (unpinned_message)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var channel = GetChannel(data.ChannelId) as ISocketMessageChannel; - - if (channel == null) - { - await UnknownChannelAsync(extraData.Type, data.ChannelId).ConfigureAwait(false); - return; - } - - var guild = (channel as SocketGuildChannel)?.Guild; - if (guild != null) - { - SocketGuildUser operatorUser = guild.GetUser(data.OperatorUserId); - if (operatorUser == null) - { - GuildMember model = await ApiClient.GetGuildMemberAsync(guild.Id, data.OperatorUserId).ConfigureAwait(false); - operatorUser = guild.AddOrUpdateUser(model); - } - - Cacheable cacheableBefore; - SocketMessage after; - - SocketUserMessage cachedMsg = channel.GetCachedMessage(data.MessageId) as SocketUserMessage; - bool isCached = cachedMsg != null; - if (isCached) + #region Channels + + // 频道内用户添加 reaction + case ("GROUP", "added_reaction"): { - SocketMessage before = cachedMsg.Clone(); - cachedMsg.IsPinned = false; - after = cachedMsg; - - cacheableBefore = new Cacheable(before, data.MessageId, true, async () => await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false)); - + await _gatewayLogger.DebugAsync("Received Event (added_reaction)").ConfigureAwait(false); + + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var channel = GetChannel(data.ChannelId) as ISocketMessageChannel; + + var cachedMsg = channel?.GetCachedMessage(data.MessageId) as SocketUserMessage; + bool isMsgCached = cachedMsg is not null; + + IUser user = channel is not null + ? await channel.GetUserAsync(data.UserId, CacheMode.CacheOnly).ConfigureAwait(false) + : GetUser(data.UserId); + + var cacheableChannel = new Cacheable(channel, data.ChannelId, channel != null, async () => await GetChannelAsync(data.ChannelId).ConfigureAwait(false) as IMessageChannel); + var cacheableMsg = new Cacheable(cachedMsg, data.MessageId, isMsgCached, async () => + { + var channelObj = await cacheableChannel.GetOrDownloadAsync().ConfigureAwait(false); + return await channelObj.GetMessageAsync(data.MessageId).ConfigureAwait(false) as IUserMessage; + }); + + var reaction = SocketReaction.Create(data, channel, cachedMsg, user); + + cachedMsg?.AddReaction(reaction); + + await TimedInvokeAsync(_reactionAddedEvent, nameof(ReactionAdded), cacheableMsg, cacheableChannel, reaction).ConfigureAwait(false); } - else + break; + + // 频道内用户取消 reaction + case ("GROUP", "deleted_reaction"): { - Message msg = await ApiClient.GetMessageAsync(data.MessageId).ConfigureAwait(false); - SocketUser author = guild.GetUser(msg.Author.Id) - ?? (SocketUser) new SocketUnknownUser(this, id: 0); - after = SocketMessage.Create(this, State, author, channel, msg); - - cacheableBefore = new Cacheable(null, data.MessageId, false, async () => await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false)); - } - await TimedInvokeAsync(_messageUnpinnedEvent, nameof(MessageUnpinned), cacheableBefore, after, channel, operatorUser).ConfigureAwait(false); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; - - #endregion + await _gatewayLogger.DebugAsync("Received Event (deleted_reaction)").ConfigureAwait(false); - #region Direct Messages + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var channel = GetChannel(data.ChannelId) as ISocketMessageChannel; - // 私聊消息更新 - case ("PERSON", "updated_private_message"): - { - await _gatewayLogger.DebugAsync("Received Event (updated_private_message)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var user = await ApiClient.GetUserAsync(data.AuthorId).ConfigureAwait(false); - var channel = CreateDMChannel(data.ChatCode, user, State); - - SocketMessage before = null, after = null; - SocketMessage cachedMsg = channel?.GetCachedMessage(data.MessageId); - bool isCached = cachedMsg != null; - if (isCached) - { - before = cachedMsg.Clone(); - cachedMsg.Update(State, data); - after = cachedMsg; - } - else - { - var msg = await ApiClient.GetDirectMessageAsync(data.MessageId, chatCode: data.ChatCode).ConfigureAwait(false); - SocketUser author = State.GetUser(msg?.AuthorId ?? 0) - ?? (SocketUser) new SocketUnknownUser(this, id: 0); - - if (channel == null) - { - await UnknownPrivateChannelAsync(extraData.Type, data.ChatCode).ConfigureAwait(false); - return; - } - - after = SocketMessage.Create(this, State, author, channel, msg); - } - var cacheableBefore = new Cacheable(before, data.MessageId, isCached, async () => await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false)); + var cachedMsg = channel?.GetCachedMessage(data.MessageId) as SocketUserMessage; + bool isMsgCached = cachedMsg is not null; - await TimedInvokeAsync(_directMessageUpdatedEvent, nameof(DirectMessageUpdated), cacheableBefore, after, channel).ConfigureAwait(false); - } - break; - - // 私聊消息被删除 - case ("PERSON", "deleted_private_message"): - { - await _gatewayLogger.DebugAsync("Received Event (deleted_private_message)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var user = await ApiClient.GetUserAsync(data.AuthorId).ConfigureAwait(false); - var channel = CreateDMChannel(data.ChatCode, user, State); - - SocketMessage msg = null; - if (channel != null) - msg = SocketChannelHelper.RemoveMessage(channel, this, data.MessageId); - var cacheableMsg = new Cacheable(msg, data.MessageId, msg != null, () => Task.FromResult((IMessage)null)); - var cacheableChannel = new Cacheable(channel, data.ChatCode, channel != null, async () => await GetDMChannelAsync(data.ChatCode).ConfigureAwait(false)); - - await TimedInvokeAsync(_directMessageDeletedEvent, nameof(DirectMessageDeleted), cacheableMsg, cacheableChannel).ConfigureAwait(false); - } - break; - - // 私聊内用户添加 reaction - case ("PERSON", "private_added_reaction"): - { - await _gatewayLogger.DebugAsync("Received Event (private_added_reaction)").ConfigureAwait(false); - - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var channel = GetDMChannel(data.ChatCode) as ISocketMessageChannel; - - var cachedMsg = channel?.GetCachedMessage(data.MessageId) as SocketUserMessage; - bool isMsgCached = cachedMsg is not null; - - IUser user = channel is not null - ? await channel.GetUserAsync(data.UserId, CacheMode.CacheOnly).ConfigureAwait(false) - : GetUser(data.UserId); - - var cacheableChannel = new Cacheable((IDMChannel) channel, data.ChatCode, channel != null, async () => await GetDMChannelAsync(data.ChatCode).ConfigureAwait(false)); - var cacheableMsg = new Cacheable(cachedMsg, data.MessageId, isMsgCached, async () => - { - var channelObj = await cacheableChannel.GetOrDownloadAsync().ConfigureAwait(false); - return await channelObj.GetMessageAsync(data.MessageId).ConfigureAwait(false) as IUserMessage; - }); - var reaction = SocketReaction.Create(data, (IDMChannel) channel, cachedMsg, user); - - cachedMsg?.AddReaction(reaction); - - await TimedInvokeAsync(_directReactionAddedEvent, nameof(DirectReactionAdded), cacheableMsg, cacheableChannel, reaction).ConfigureAwait(false); - } - break; - - // 私聊内用户取消 reaction - case ("PERSON", "private_deleted_reaction"): - { - await _gatewayLogger.DebugAsync("Received Event (private_deleted_reaction)").ConfigureAwait(false); - - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var channel = GetDMChannel(data.ChatCode) as ISocketMessageChannel; - - var cachedMsg = channel?.GetCachedMessage(data.MessageId) as SocketUserMessage; - bool isMsgCached = cachedMsg is not null; - - IUser user = channel is not null - ? await channel.GetUserAsync(data.UserId, CacheMode.CacheOnly).ConfigureAwait(false) - : GetUser(data.UserId); - - var cacheableChannel = new Cacheable((IDMChannel) channel, data.ChatCode, channel != null, async () => await GetDMChannelAsync(data.ChatCode).ConfigureAwait(false)); - var cacheableMsg = new Cacheable(cachedMsg, data.MessageId, isMsgCached, async () => - { - var channelObj = await cacheableChannel.GetOrDownloadAsync().ConfigureAwait(false); - return await channelObj.GetMessageAsync(data.MessageId).ConfigureAwait(false) as IUserMessage; - }); - var reaction = SocketReaction.Create(data, (IDMChannel) channel, cachedMsg, user); - - cachedMsg?.RemoveReaction(reaction); - - await TimedInvokeAsync(_directReactionRemovedEvent, nameof(DirectReactionRemoved), cacheableMsg, cacheableChannel, reaction).ConfigureAwait(false); - } - break; + IUser user = channel is not null + ? await channel.GetUserAsync(data.UserId, CacheMode.CacheOnly).ConfigureAwait(false) + : GetUser(data.UserId); - #endregion + var cacheableChannel = new Cacheable(channel, data.ChannelId, channel != null, async () => await GetChannelAsync(data.ChannelId).ConfigureAwait(false) as IMessageChannel); + var cacheableMsg = new Cacheable(cachedMsg, data.MessageId, isMsgCached, async () => + { + var channelObj = await cacheableChannel.GetOrDownloadAsync().ConfigureAwait(false); + return await channelObj.GetMessageAsync(data.MessageId).ConfigureAwait(false) as IUserMessage; + }); + var reaction = SocketReaction.Create(data, channel, cachedMsg, user); - #region Guild Members + cachedMsg?.RemoveReaction(reaction); - // 新成员加入服务器 - case ("GROUP", "joined_guild"): - { - await _gatewayLogger.DebugAsync("Received Event (joined_guild)").ConfigureAwait(false); - var guild = State.GetGuild(gatewayEvent.TargetId); - if (guild != null) - { - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - GuildMember model = await ApiClient.GetGuildMemberAsync(guild.Id, data.UserId).ConfigureAwait(false); - SocketGuildUser user = guild.AddOrUpdateUser(model); - guild.MemberCount++; - await TimedInvokeAsync(_userJoinedEvent, nameof(UserJoined), user, data.JoinedAt).ConfigureAwait(false); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; - - // 服务器成员退出 - case ("GROUP", "exited_guild"): - { - await _gatewayLogger.DebugAsync("Received Event (exited_guild)").ConfigureAwait(false); - var guild = State.GetGuild(gatewayEvent.TargetId); - if (guild != null) - { - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - SocketUser user = guild.RemoveUser(data.UserId); - guild.MemberCount--; - - user ??= State.GetUser(data.UserId); - - User model = await ApiClient.GetUserAsync(data.UserId).ConfigureAwait(false); - if (user != null) + await TimedInvokeAsync(_reactionRemovedEvent, nameof(ReactionRemoved), cacheableMsg, cacheableChannel, reaction).ConfigureAwait(false); + } + break; + + // 频道消息更新 + case ("GROUP", "updated_message"): { - user.Update(State, model); - user.UpdatePresence(model.Online, model.OperatingSystem); + await _gatewayLogger.DebugAsync("Received Event (updated_message)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var channel = GetChannel(data.ChannelId) as ISocketMessageChannel; + var guild = (channel as SocketGuildChannel)?.Guild; + + SocketMessage before = null, after = null; + SocketMessage cachedMsg = channel?.GetCachedMessage(data.MessageId); + bool isCached = cachedMsg != null; + if (isCached) + { + before = cachedMsg.Clone(); + cachedMsg.Update(State, data); + after = cachedMsg; + } + else + { + Message msg = await ApiClient.GetMessageAsync(data.MessageId).ConfigureAwait(false); + + SocketUser author = guild.GetUser(msg.Author.Id) + ?? (SocketUser)new SocketUnknownUser(this, id: 0); + + if (channel == null) + { + await UnknownChannelAsync(extraData.Type, data.ChannelId).ConfigureAwait(false); + return; + } + + after = SocketMessage.Create(this, State, author, channel, msg); + } + var cacheableBefore = new Cacheable(before, data.MessageId, isCached, async () => await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false)); + + await TimedInvokeAsync(_messageUpdatedEvent, nameof(MessageUpdated), cacheableBefore, after, channel).ConfigureAwait(false); } - else - user = State.GetOrAddUser(data.UserId, _ => SocketGlobalUser.Create(this, State, model)); - - await TimedInvokeAsync(_userLeftEvent, nameof(UserLeft), guild, user, data.ExitedAt).ConfigureAwait(false); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; - - // 服务器成员信息更新 - case ("GROUP", "updated_guild_member"): - { - await _gatewayLogger.DebugAsync("Received Event (updated_guild_member)").ConfigureAwait(false); - var guild = State.GetGuild(gatewayEvent.TargetId); - if (guild != null) - { - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - SocketGuildUser user = guild.GetUser(data.UserId); + break; - if (user != null) + // 频道消息被删除 + case ("GROUP", "deleted_message"): { - // var globalBefore = user.GlobalUser.Clone(); - // if (user.GlobalUser.Update(State, model)) - // { - // //Global data was updated, trigger UserUpdated - // await TimedInvokeAsync(_userUpdatedEvent, nameof(UserUpdated), globalBefore, user).ConfigureAwait(false); - // } - - var before = user.Clone(); - user.Update(State, data); - - var cacheableBefore = new Cacheable(before, user.Id, true, () => Task.FromResult(null)); - await TimedInvokeAsync(_guildMemberUpdatedEvent, nameof(GuildMemberUpdated), cacheableBefore, user).ConfigureAwait(false); + await _gatewayLogger.DebugAsync("Received Event (deleted_message)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var channel = GetChannel(data.ChannelId) as ISocketMessageChannel; + var guild = (channel as SocketGuildChannel)?.Guild; + + SocketMessage msg = null; + if (channel != null) + msg = SocketChannelHelper.RemoveMessage(channel, this, data.MessageId); + var cacheableMsg = new Cacheable(msg, data.MessageId, msg != null, () => Task.FromResult((IMessage)null)); + var cacheableChannel = new Cacheable(channel, data.ChannelId, channel != null, async () => await GetChannelAsync(data.ChannelId).ConfigureAwait(false) as IMessageChannel); + + await TimedInvokeAsync(_messageDeletedEvent, nameof(MessageDeleted), cacheableMsg, cacheableChannel).ConfigureAwait(false); } - else + break; + + // 新增频道 + case ("GROUP", "added_channel"): { - GuildMember model = await ApiClient.GetGuildMemberAsync(guild.Id, data.UserId).ConfigureAwait(false); - user = guild.AddOrUpdateUser(model); - var cacheableBefore = new Cacheable(null, user.Id, false, () => Task.FromResult(null)); - await TimedInvokeAsync(_guildMemberUpdatedEvent, nameof(GuildMemberUpdated), cacheableBefore, user).ConfigureAwait(false); + await _gatewayLogger.DebugAsync("Received Event (added_channel)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + SocketChannel channel = null; + var guild = State.GetGuild(data.GuildId); + if (guild != null) + { + channel = guild.AddChannel(State, data); + } + else + { + await UnknownGuildAsync(extraData.Type, data.GuildId).ConfigureAwait(false); + return; + } + if (channel != null) + await TimedInvokeAsync(_channelCreatedEvent, nameof(ChannelCreated), channel).ConfigureAwait(false); } - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; - - // 服务器成员上线 - case ("PERSON", "guild_member_online"): - { - await _gatewayLogger.DebugAsync("Received Event (guild_member_online)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - List users = new(); - foreach (var guildId in data.CommonGuilds) - { - var guild = State.GetGuild(guildId); - if (guild != null) + break; + + // 修改频道信息 + case ("GROUP", "updated_channel"): { - SocketGuildUser user = guild.GetUser(data.UserId) ?? guild.AddOrUpdateUser(await ApiClient - .GetGuildMemberAsync(guild.Id, data.UserId).ConfigureAwait(false)); - user.Presence.Update(true); - users.Add(user); + await _gatewayLogger.DebugAsync("Received Event (updated_channel)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var channel = State.GetChannel(data.Id); + if (channel != null) + { + var before = channel.Clone(); + channel.Update(State, data); + + var guild = (channel as SocketGuildChannel)?.Guild; + await TimedInvokeAsync(_channelUpdatedEvent, nameof(ChannelUpdated), before, channel).ConfigureAwait(false); + } + else + { + await UnknownChannelAsync(extraData.Type, data.Id).ConfigureAwait(false); + return; + } } - else + break; + + // 删除频道 + case ("GROUP", "deleted_channel"): { - await UnknownGuildAsync(extraData.Type, guildId).ConfigureAwait(false); - return; + await _gatewayLogger.DebugAsync("Received Event (deleted_channel)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var channel = State.GetChannel(data.ChannelId); + + var guild = (channel as SocketGuildChannel)?.Guild; + if (guild != null) + { + channel = guild.RemoveChannel(State, data.ChannelId); + + } + else + { + await UnknownGuildAsync(extraData.Type, guildId: 0).ConfigureAwait(false); + return; + } + + if (channel != null) + await TimedInvokeAsync(_channelDestroyedEvent, nameof(ChannelDestroyed), channel).ConfigureAwait(false); + else + { + await UnknownChannelAsync(extraData.Type, data.ChannelId, guild?.Id ?? 0).ConfigureAwait(false); + return; + } } - } - await TimedInvokeAsync(_guildMemberOnlineEvent, nameof(GuildMemberOnline), users, data.OnlineAt).ConfigureAwait(false); - } - break; - - // 服务器成员下线 - case ("PERSON", "guild_member_offline"): - { - await _gatewayLogger.DebugAsync("Received Event (guild_member_offline)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - List users = new(); - foreach (var guildId in data.CommonGuilds) - { - var guild = State.GetGuild(guildId); - if (guild != null) + break; + + // 新的频道置顶消息 + case ("GROUP", "pinned_message"): { - SocketGuildUser user = guild.GetUser(data.UserId) ?? guild.AddOrUpdateUser(await ApiClient - .GetGuildMemberAsync(guild.Id, data.UserId).ConfigureAwait(false)); - user.Presence.Update(false); - users.Add(user); + await _gatewayLogger.DebugAsync("Received Event (pinned_message)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var channel = GetChannel(data.ChannelId) as ISocketMessageChannel; + + if (channel == null) + { + await UnknownChannelAsync(extraData.Type, data.ChannelId).ConfigureAwait(false); + return; + } + + var guild = (channel as SocketGuildChannel)?.Guild; + if (guild != null) + { + SocketGuildUser operatorUser = guild.GetUser(data.OperatorUserId); + if (operatorUser == null) + { + GuildMember model = await ApiClient.GetGuildMemberAsync(guild.Id, data.OperatorUserId).ConfigureAwait(false); + operatorUser = guild.AddOrUpdateUser(model); + } + + Cacheable cacheableBefore; + SocketMessage after; + + SocketUserMessage cachedMsg = channel.GetCachedMessage(data.MessageId) as SocketUserMessage; + bool isCached = cachedMsg != null; + if (isCached) + { + SocketMessage before = cachedMsg.Clone(); + cachedMsg.IsPinned = true; + after = cachedMsg; + + cacheableBefore = new Cacheable(before, data.MessageId, true, async () => await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false)); + + } + else + { + Message msg = await ApiClient.GetMessageAsync(data.MessageId).ConfigureAwait(false); + SocketUser author = guild.GetUser(msg.Author.Id) + ?? (SocketUser)new SocketUnknownUser(this, id: 0); + after = SocketMessage.Create(this, State, author, channel, msg); + + cacheableBefore = new Cacheable(null, data.MessageId, false, async () => await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false)); + } + await TimedInvokeAsync(_messagePinnedEvent, nameof(MessagePinned), cacheableBefore, after, channel, operatorUser).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } } - else + break; + + // 取消频道置顶消息 + case ("GROUP", "unpinned_message"): { - await UnknownGuildAsync(extraData.Type, guildId).ConfigureAwait(false); - return; + await _gatewayLogger.DebugAsync("Received Event (unpinned_message)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var channel = GetChannel(data.ChannelId) as ISocketMessageChannel; + + if (channel == null) + { + await UnknownChannelAsync(extraData.Type, data.ChannelId).ConfigureAwait(false); + return; + } + + var guild = (channel as SocketGuildChannel)?.Guild; + if (guild != null) + { + SocketGuildUser operatorUser = guild.GetUser(data.OperatorUserId); + if (operatorUser == null) + { + GuildMember model = await ApiClient.GetGuildMemberAsync(guild.Id, data.OperatorUserId).ConfigureAwait(false); + operatorUser = guild.AddOrUpdateUser(model); + } + + Cacheable cacheableBefore; + SocketMessage after; + + SocketUserMessage cachedMsg = channel.GetCachedMessage(data.MessageId) as SocketUserMessage; + bool isCached = cachedMsg != null; + if (isCached) + { + SocketMessage before = cachedMsg.Clone(); + cachedMsg.IsPinned = false; + after = cachedMsg; + + cacheableBefore = new Cacheable(before, data.MessageId, true, async () => await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false)); + + } + else + { + Message msg = await ApiClient.GetMessageAsync(data.MessageId).ConfigureAwait(false); + SocketUser author = guild.GetUser(msg.Author.Id) + ?? (SocketUser)new SocketUnknownUser(this, id: 0); + after = SocketMessage.Create(this, State, author, channel, msg); + + cacheableBefore = new Cacheable(null, data.MessageId, false, async () => await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false)); + } + await TimedInvokeAsync(_messageUnpinnedEvent, nameof(MessageUnpinned), cacheableBefore, after, channel, operatorUser).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } } - } - await TimedInvokeAsync(_guildMemberOfflineEvent, nameof(GuildMemberOffline), users, data.OfflineAt).ConfigureAwait(false); - } - break; + break; - #endregion + #endregion - #region Guild Roles + #region Direct Messages - // 服务器角色增加 - case ("GROUP", "added_role"): - { - await _gatewayLogger.DebugAsync("Received Event (added_role)").ConfigureAwait(false); - - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var guild = State.GetGuild(gatewayEvent.TargetId); - if (guild != null) - { - var role = guild.AddRole(data); - await TimedInvokeAsync(_roleCreatedEvent, nameof(RoleCreated), role).ConfigureAwait(false); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; - - // 服务器角色删除 - case ("GROUP", "deleted_role"): - { - await _gatewayLogger.DebugAsync("Received Event (deleted_role)").ConfigureAwait(false); - - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var guild = State.GetGuild(gatewayEvent.TargetId); - if (guild != null) - { - var role = guild.RemoveRole(data.Id); - await TimedInvokeAsync(_roleDeletedEvent, nameof(RoleDeleted), role).ConfigureAwait(false); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; - - // 服务器角色更新 - case ("GROUP", "updated_role"): - { - await _gatewayLogger.DebugAsync("Received Event (updated_role)").ConfigureAwait(false); + // 私聊消息更新 + case ("PERSON", "updated_private_message"): + { + await _gatewayLogger.DebugAsync("Received Event (updated_private_message)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var user = await ApiClient.GetUserAsync(data.AuthorId).ConfigureAwait(false); + var channel = CreateDMChannel(data.ChatCode, user, State); + + SocketMessage before = null, after = null; + SocketMessage cachedMsg = channel?.GetCachedMessage(data.MessageId); + bool isCached = cachedMsg != null; + if (isCached) + { + before = cachedMsg.Clone(); + cachedMsg.Update(State, data); + after = cachedMsg; + } + else + { + var msg = await ApiClient.GetDirectMessageAsync(data.MessageId, chatCode: data.ChatCode).ConfigureAwait(false); + SocketUser author = State.GetUser(msg?.AuthorId ?? 0) + ?? (SocketUser)new SocketUnknownUser(this, id: 0); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var guild = State.GetGuild(gatewayEvent.TargetId); - if (guild != null) - { - var role = guild.GetRole(data.Id); - if (role != null) + if (channel == null) + { + await UnknownPrivateChannelAsync(extraData.Type, data.ChatCode).ConfigureAwait(false); + return; + } + + after = SocketMessage.Create(this, State, author, channel, msg); + } + var cacheableBefore = new Cacheable(before, data.MessageId, isCached, async () => await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false)); + + await TimedInvokeAsync(_directMessageUpdatedEvent, nameof(DirectMessageUpdated), cacheableBefore, after, channel).ConfigureAwait(false); + } + break; + + // 私聊消息被删除 + case ("PERSON", "deleted_private_message"): + { + await _gatewayLogger.DebugAsync("Received Event (deleted_private_message)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var user = await ApiClient.GetUserAsync(data.AuthorId).ConfigureAwait(false); + var channel = CreateDMChannel(data.ChatCode, user, State); + + SocketMessage msg = null; + if (channel != null) + msg = SocketChannelHelper.RemoveMessage(channel, this, data.MessageId); + var cacheableMsg = new Cacheable(msg, data.MessageId, msg != null, () => Task.FromResult((IMessage)null)); + var cacheableChannel = new Cacheable(channel, data.ChatCode, channel != null, async () => await GetDMChannelAsync(data.ChatCode).ConfigureAwait(false)); + + await TimedInvokeAsync(_directMessageDeletedEvent, nameof(DirectMessageDeleted), cacheableMsg, cacheableChannel).ConfigureAwait(false); + } + break; + + // 私聊内用户添加 reaction + case ("PERSON", "private_added_reaction"): { - var before = role.Clone(); - role.Update(State, data); + await _gatewayLogger.DebugAsync("Received Event (private_added_reaction)").ConfigureAwait(false); + + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var channel = GetDMChannel(data.ChatCode) as ISocketMessageChannel; - await TimedInvokeAsync(_roleUpdatedEvent, nameof(RoleUpdated), before, role).ConfigureAwait(false); + var cachedMsg = channel?.GetCachedMessage(data.MessageId) as SocketUserMessage; + bool isMsgCached = cachedMsg is not null; + + IUser user = channel is not null + ? await channel.GetUserAsync(data.UserId, CacheMode.CacheOnly).ConfigureAwait(false) + : GetUser(data.UserId); + + var cacheableChannel = new Cacheable((IDMChannel)channel, data.ChatCode, channel != null, async () => await GetDMChannelAsync(data.ChatCode).ConfigureAwait(false)); + var cacheableMsg = new Cacheable(cachedMsg, data.MessageId, isMsgCached, async () => + { + var channelObj = await cacheableChannel.GetOrDownloadAsync().ConfigureAwait(false); + return await channelObj.GetMessageAsync(data.MessageId).ConfigureAwait(false) as IUserMessage; + }); + var reaction = SocketReaction.Create(data, (IDMChannel)channel, cachedMsg, user); + + cachedMsg?.AddReaction(reaction); + + await TimedInvokeAsync(_directReactionAddedEvent, nameof(DirectReactionAdded), cacheableMsg, cacheableChannel, reaction).ConfigureAwait(false); } - else + break; + + // 私聊内用户取消 reaction + case ("PERSON", "private_deleted_reaction"): { - await UnknownRoleAsync(extraData.Type, data.Id, guild.Id).ConfigureAwait(false); - return; + await _gatewayLogger.DebugAsync("Received Event (private_deleted_reaction)").ConfigureAwait(false); + + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var channel = GetDMChannel(data.ChatCode) as ISocketMessageChannel; + + var cachedMsg = channel?.GetCachedMessage(data.MessageId) as SocketUserMessage; + bool isMsgCached = cachedMsg is not null; + + IUser user = channel is not null + ? await channel.GetUserAsync(data.UserId, CacheMode.CacheOnly).ConfigureAwait(false) + : GetUser(data.UserId); + + var cacheableChannel = new Cacheable((IDMChannel)channel, data.ChatCode, channel != null, async () => await GetDMChannelAsync(data.ChatCode).ConfigureAwait(false)); + var cacheableMsg = new Cacheable(cachedMsg, data.MessageId, isMsgCached, async () => + { + var channelObj = await cacheableChannel.GetOrDownloadAsync().ConfigureAwait(false); + return await channelObj.GetMessageAsync(data.MessageId).ConfigureAwait(false) as IUserMessage; + }); + var reaction = SocketReaction.Create(data, (IDMChannel)channel, cachedMsg, user); + + cachedMsg?.RemoveReaction(reaction); + + await TimedInvokeAsync(_directReactionRemovedEvent, nameof(DirectReactionRemoved), cacheableMsg, cacheableChannel, reaction).ConfigureAwait(false); } - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; + break; - #endregion + #endregion - #region Guild Emojis + #region Guild Members - // 服务器表情新增 - case ("GROUP", "added_emoji"): - { - await _gatewayLogger.DebugAsync("Received Event (added_emoji)").ConfigureAwait(false); - - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var guild = State.GetGuild(gatewayEvent.TargetId); - if (guild != null) - { - var emote = guild.AddEmote(data); - await TimedInvokeAsync(_emoteCreatedEvent, nameof(EmoteCreated), emote, guild).ConfigureAwait(false); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; - - // 服务器表情更新 - case ("GROUP", "updated_emoji"): - { - await _gatewayLogger.DebugAsync("Received Event (updated_emoji)").ConfigureAwait(false); - - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var guild = State.GetGuild(gatewayEvent.TargetId); - if (guild != null) - { - var emote = guild.GetEmote(data?.Id); - var before = emote.Clone(); - var after = guild.AddOrUpdateEmote(data); - await TimedInvokeAsync(_emoteUpdatedEvent, nameof(EmoteUpdated), before, after, guild).ConfigureAwait(false); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; - - // 服务器表情删除 - case ("GROUP", "deleted_emoji"): - { - await _gatewayLogger.DebugAsync("Received Event (deleted_emoji)").ConfigureAwait(false); - - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var guild = State.GetGuild(gatewayEvent.TargetId); - if (guild != null) - { - var emote = guild.RemoveEmote(data?.Id); - await TimedInvokeAsync(_emoteDeletedEvent, nameof(EmoteDeleted), emote, guild).ConfigureAwait(false); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; + // 新成员加入服务器 + case ("GROUP", "joined_guild"): + { + await _gatewayLogger.DebugAsync("Received Event (joined_guild)").ConfigureAwait(false); + var guild = State.GetGuild(gatewayEvent.TargetId); + if (guild != null) + { + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + GuildMember model = await ApiClient.GetGuildMemberAsync(guild.Id, data.UserId).ConfigureAwait(false); + SocketGuildUser user = guild.AddOrUpdateUser(model); + guild.MemberCount++; + await TimedInvokeAsync(_userJoinedEvent, nameof(UserJoined), user, data.JoinedAt).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } + } + break; - #endregion + // 服务器成员退出 + case ("GROUP", "exited_guild"): + { + await _gatewayLogger.DebugAsync("Received Event (exited_guild)").ConfigureAwait(false); + var guild = State.GetGuild(gatewayEvent.TargetId); + if (guild != null) + { + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + SocketUser user = guild.RemoveUser(data.UserId); + guild.MemberCount--; + + user ??= State.GetUser(data.UserId); + + User model = await ApiClient.GetUserAsync(data.UserId).ConfigureAwait(false); + if (user != null) + { + user.Update(State, model); + user.UpdatePresence(model.Online, model.OperatingSystem); + } + else + user = State.GetOrAddUser(data.UserId, _ => SocketGlobalUser.Create(this, State, model)); + + await TimedInvokeAsync(_userLeftEvent, nameof(UserLeft), guild, user, data.ExitedAt).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } + } + break; - #region Guilds + // 服务器成员信息更新 + case ("GROUP", "updated_guild_member"): + { + await _gatewayLogger.DebugAsync("Received Event (updated_guild_member)").ConfigureAwait(false); + var guild = State.GetGuild(gatewayEvent.TargetId); + if (guild != null) + { + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + SocketGuildUser user = guild.GetUser(data.UserId); + + if (user != null) + { + // var globalBefore = user.GlobalUser.Clone(); + // if (user.GlobalUser.Update(State, model)) + // { + // //Global data was updated, trigger UserUpdated + // await TimedInvokeAsync(_userUpdatedEvent, nameof(UserUpdated), globalBefore, user).ConfigureAwait(false); + // } + + var before = user.Clone(); + user.Update(State, data); + + var cacheableBefore = new Cacheable(before, user.Id, true, () => Task.FromResult(null)); + await TimedInvokeAsync(_guildMemberUpdatedEvent, nameof(GuildMemberUpdated), cacheableBefore, user).ConfigureAwait(false); + } + else + { + GuildMember model = await ApiClient.GetGuildMemberAsync(guild.Id, data.UserId).ConfigureAwait(false); + user = guild.AddOrUpdateUser(model); + var cacheableBefore = new Cacheable(null, user.Id, false, () => Task.FromResult(null)); + await TimedInvokeAsync(_guildMemberUpdatedEvent, nameof(GuildMemberUpdated), cacheableBefore, user).ConfigureAwait(false); + } + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } + } + break; - // 服务器信息更新 - case ("GROUP", "updated_guild"): - { - await _gatewayLogger.DebugAsync("Received Event (updated_guild)").ConfigureAwait(false); + // 服务器成员上线 + case ("PERSON", "guild_member_online"): + { + await _gatewayLogger.DebugAsync("Received Event (guild_member_online)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + List users = new(); + foreach (var guildId in data.CommonGuilds) + { + var guild = State.GetGuild(guildId); + if (guild != null) + { + SocketGuildUser user = guild.GetUser(data.UserId) ?? guild.AddOrUpdateUser(await ApiClient + .GetGuildMemberAsync(guild.Id, data.UserId).ConfigureAwait(false)); + user.Presence.Update(true); + users.Add(user); + } + else + { + await UnknownGuildAsync(extraData.Type, guildId).ConfigureAwait(false); + return; + } + } + await TimedInvokeAsync(_guildMemberOnlineEvent, nameof(GuildMemberOnline), users, data.OnlineAt).ConfigureAwait(false); + } + break; - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var guild = State.GetGuild(data.GuildId); - if (guild != null) - { - var before = guild.Clone(); - guild.Update(State, data); - if (AlwaysDownloadBoostSubscriptions && - (before.BoostSubscriptionCount != guild.BoostSubscriptionCount - || before.BufferBoostSubscriptionCount != guild.BufferBoostSubscriptionCount)) - await guild.DownloadBoostSubscriptionsAsync().ConfigureAwait(false); - await TimedInvokeAsync(_guildUpdatedEvent, nameof(GuildUpdated), before, guild).ConfigureAwait(false); - } - else - { - await UnknownGuildAsync(extraData.Type, data.GuildId).ConfigureAwait(false); - return; - } - } - break; - - // 服务器删除 - case ("GROUP", "deleted_guild"): - { - await _gatewayLogger.DebugAsync("Received Event (deleted_guild)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); + // 服务器成员下线 + case ("PERSON", "guild_member_offline"): + { + await _gatewayLogger.DebugAsync("Received Event (guild_member_offline)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + List users = new(); + foreach (var guildId in data.CommonGuilds) + { + var guild = State.GetGuild(guildId); + if (guild != null) + { + SocketGuildUser user = guild.GetUser(data.UserId) ?? guild.AddOrUpdateUser(await ApiClient + .GetGuildMemberAsync(guild.Id, data.UserId).ConfigureAwait(false)); + user.Presence.Update(false); + users.Add(user); + } + else + { + await UnknownGuildAsync(extraData.Type, guildId).ConfigureAwait(false); + return; + } + } + await TimedInvokeAsync(_guildMemberOfflineEvent, nameof(GuildMemberOffline), users, data.OfflineAt).ConfigureAwait(false); + } + break; - var guild = RemoveGuild(data.GuildId); - if (guild != null) - { - await GuildUnavailableAsync(guild).ConfigureAwait(false); - await TimedInvokeAsync(_leftGuildEvent, nameof(LeftGuild), guild).ConfigureAwait(false); - ((IDisposable) guild).Dispose(); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; - - // 服务器封禁用户 - case ("GROUP", "added_block_list"): - { - await _gatewayLogger.DebugAsync("Received Event (added_block_list)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var guild = State.GetGuild(gatewayEvent.TargetId); - if (guild != null) - { - SocketUser operatorUser = guild.GetUser(data.OperatorUserId) - ?? (SocketUser) SocketUnknownUser.Create(this, State, data.OperatorUserId); - var bannedUsers = data.UserIds.Select(id => guild.GetUser(id) - ?? (SocketUser) SocketUnknownUser.Create(this, State, id)) - .ToReadOnlyCollection(() => data.UserIds.Length); - await TimedInvokeAsync(_userBannedEvent, nameof(UserBanned), bannedUsers, operatorUser, guild).ConfigureAwait(false); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; - - // 服务器取消封禁用户 - case ("GROUP", "deleted_block_list"): - { - await _gatewayLogger.DebugAsync("Received Event (deleted_block_list)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var guild = State.GetGuild(gatewayEvent.TargetId); - if (guild != null) - { - SocketUser operatorUser = guild.GetUser(data.OperatorUserId) - ?? (SocketUser) SocketUnknownUser.Create(this, State, data.OperatorUserId); - var unbannedUsers = data.UserIds.Select(id => guild.GetUser(id) - ?? (SocketUser) SocketUnknownUser.Create(this, State, id)) - .ToReadOnlyCollection(() => data.UserIds.Length); - await TimedInvokeAsync(_userUnbannedEvent, nameof(UserUnbanned), unbannedUsers, operatorUser, guild).ConfigureAwait(false); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; + #endregion - #endregion + #region Guild Roles - #region Users + // 服务器角色增加 + case ("GROUP", "added_role"): + { + await _gatewayLogger.DebugAsync("Received Event (added_role)").ConfigureAwait(false); - // 用户加入语音频道 - case ("GROUP", "joined_channel"): - { - await _gatewayLogger.DebugAsync("Received Event (joined_channel)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var guild = State.GetGuild(gatewayEvent.TargetId); - if (guild != null) - { - var channel = GetChannel(data.ChannelId) as SocketVoiceChannel; - - if (channel == null) + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var guild = State.GetGuild(gatewayEvent.TargetId); + if (guild != null) + { + var role = guild.AddRole(data); + await TimedInvokeAsync(_roleCreatedEvent, nameof(RoleCreated), role).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } + } + break; + + // 服务器角色删除 + case ("GROUP", "deleted_role"): { - await UnknownChannelAsync(extraData.Type, data.ChannelId).ConfigureAwait(false); - return; + await _gatewayLogger.DebugAsync("Received Event (deleted_role)").ConfigureAwait(false); + + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var guild = State.GetGuild(gatewayEvent.TargetId); + if (guild != null) + { + var role = guild.RemoveRole(data.Id); + await TimedInvokeAsync(_roleDeletedEvent, nameof(RoleDeleted), role).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } } - - var user = guild.GetUser(data.UserId) - ?? SocketUnknownUser.Create(this, State, data.UserId) as SocketUser; - guild.AddOrUpdateVoiceState(user.Id, channel.Id); - - await TimedInvokeAsync(_userConnectedEvent, nameof(UserConnected), user, channel, guild, data.At).ConfigureAwait(false); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; - - // 用户退出语音频道 - case ("GROUP", "exited_channel"): - { - await _gatewayLogger.DebugAsync("Received Event (exited_channel)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - var guild = State.GetGuild(gatewayEvent.TargetId); - if (guild != null) - { - var channel = GetChannel(data.ChannelId) as SocketVoiceChannel; - - if (channel == null) + break; + + // 服务器角色更新 + case ("GROUP", "updated_role"): { - await UnknownChannelAsync(extraData.Type, data.ChannelId).ConfigureAwait(false); - return; + await _gatewayLogger.DebugAsync("Received Event (updated_role)").ConfigureAwait(false); + + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var guild = State.GetGuild(gatewayEvent.TargetId); + if (guild != null) + { + var role = guild.GetRole(data.Id); + if (role != null) + { + var before = role.Clone(); + role.Update(State, data); + + await TimedInvokeAsync(_roleUpdatedEvent, nameof(RoleUpdated), before, role).ConfigureAwait(false); + } + else + { + await UnknownRoleAsync(extraData.Type, data.Id, guild.Id).ConfigureAwait(false); + return; + } + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } } - - var user = guild.GetUser(data.UserId) - ?? SocketUnknownUser.Create(this, State, data.UserId) as SocketUser; - guild.AddOrUpdateVoiceState(user.Id, voiceChannelId: null); - - await TimedInvokeAsync(_userDisconnectedEvent, nameof(UserDisconnected), user, channel, guild, data.At).ConfigureAwait(false); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; - - // 用户信息更新 - case ("PERSON", "user_updated"): - { - await _gatewayLogger.DebugAsync("Received Event (user_updated)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - if (data.UserId == CurrentUser.Id) - { - var before = CurrentUser.Clone(); - CurrentUser.Update(State, data); - await TimedInvokeAsync(_selfUpdatedEvent, nameof(CurrentUserUpdated), before, CurrentUser).ConfigureAwait(false); - } - else - { - SocketUser user = GetUser(data.UserId); - var before = user.Clone(); - user.Update(State, data); - await TimedInvokeAsync(_userUpdatedEvent, nameof(UserUpdated), before, CurrentUser).ConfigureAwait(false); - } - } - break; - - // 自己新加入服务器 - case ("PERSON", "self_joined_guild"): - { - await _gatewayLogger.DebugAsync("Received Event (self_joined_guild)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); + break; - var task = new Func>(async id => - { - int maxRetryTime = 5; - while (true) + #endregion + + #region Guild Emojis + + // 服务器表情新增 + case ("GROUP", "added_emoji"): { - try { return await ApiClient.GetGuildAsync(id).ConfigureAwait(false); } - catch (HttpException ex) when (ex.HttpCode == HttpStatusCode.Forbidden) { if (--maxRetryTime == 0) throw; } - await Task.Delay(500).ConfigureAwait(false); + await _gatewayLogger.DebugAsync("Received Event (added_emoji)").ConfigureAwait(false); + + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var guild = State.GetGuild(gatewayEvent.TargetId); + if (guild != null) + { + var emote = guild.AddEmote(data); + await TimedInvokeAsync(_emoteCreatedEvent, nameof(EmoteCreated), emote, guild).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } } - }); - - ExtendedGuild model = await task(data.GuildId).ConfigureAwait(false); - var guild = AddGuild(model, State); - guild.Update(State, model); - await TimedInvokeAsync(_joinedGuildEvent, nameof(JoinedGuild), guild).ConfigureAwait(false); - await GuildAvailableAsync(guild).ConfigureAwait(false); - } - break; - - // 自己退出服务器 - case ("PERSON", "self_exited_guild"): - { - await _gatewayLogger.DebugAsync("Received Event (self_exited_guild)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); + break; - var guild = RemoveGuild(data.GuildId); - if (guild != null) - { - await GuildUnavailableAsync(guild).ConfigureAwait(false); - await TimedInvokeAsync(_leftGuildEvent, nameof(LeftGuild), guild).ConfigureAwait(false); - ((IDisposable) guild).Dispose(); - } - else - { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; - } - } - break; + // 服务器表情更新 + case ("GROUP", "updated_emoji"): + { + await _gatewayLogger.DebugAsync("Received Event (updated_emoji)").ConfigureAwait(false); + + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var guild = State.GetGuild(gatewayEvent.TargetId); + if (guild != null) + { + var emote = guild.GetEmote(data?.Id); + var before = emote.Clone(); + var after = guild.AddOrUpdateEmote(data); + await TimedInvokeAsync(_emoteUpdatedEvent, nameof(EmoteUpdated), before, after, guild).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } + } + break; - #endregion + // 服务器表情删除 + case ("GROUP", "deleted_emoji"): + { + await _gatewayLogger.DebugAsync("Received Event (deleted_emoji)").ConfigureAwait(false); - #region Interactions + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var guild = State.GetGuild(gatewayEvent.TargetId); + if (guild != null) + { + var emote = guild.RemoveEmote(data?.Id); + await TimedInvokeAsync(_emoteDeletedEvent, nameof(EmoteDeleted), emote, guild).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } + } + break; - // Card 消息中的 Button 点击事件 - case ("PERSON", "message_btn_click"): - { - await _gatewayLogger.DebugAsync("Received Event (message_btn_click)").ConfigureAwait(false); - var data = ((JsonElement) extraData.Body).Deserialize(_serializerOptions); - if (data.GuildId.HasValue) - { - SocketTextChannel channel = GetChannel(data.ChannelId) as SocketTextChannel; - SocketGuild guild = GetGuild(data.GuildId.Value); - if (guild != null) + #endregion + + #region Guilds + + // 服务器信息更新 + case ("GROUP", "updated_guild"): { - if (channel == null) + await _gatewayLogger.DebugAsync("Received Event (updated_guild)").ConfigureAwait(false); + + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var guild = State.GetGuild(data.GuildId); + if (guild != null) { - await UnknownChannelAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + var before = guild.Clone(); + guild.Update(State, data); + if (AlwaysDownloadBoostSubscriptions && + (before.BoostSubscriptionCount != guild.BoostSubscriptionCount + || before.BufferBoostSubscriptionCount != guild.BufferBoostSubscriptionCount)) + await guild.DownloadBoostSubscriptionsAsync().ConfigureAwait(false); + await TimedInvokeAsync(_guildUpdatedEvent, nameof(GuildUpdated), before, guild).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, data.GuildId).ConfigureAwait(false); return; } - SocketUser user = channel.GetUser(data.UserId) - ?? SocketUnknownUser.Create(this, State, data.UserId) as SocketUser; - IMessage msg = await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false); - await TimedInvokeAsync(_messageButtonClickedEvent, nameof(MessageButtonClicked), data.Value, user, msg, channel, guild).ConfigureAwait(false); } - else + break; + + // 服务器删除 + case ("GROUP", "deleted_guild"): { - await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; + await _gatewayLogger.DebugAsync("Received Event (deleted_guild)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + + var guild = RemoveGuild(data.GuildId); + if (guild != null) + { + await GuildUnavailableAsync(guild).ConfigureAwait(false); + await TimedInvokeAsync(_leftGuildEvent, nameof(LeftGuild), guild).ConfigureAwait(false); + ((IDisposable)guild).Dispose(); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } } - } - else - { - SocketUser user = GetUser(data.UserId) - ?? SocketUnknownUser.Create(this, State, data.UserId); - SocketDMChannel channel = await user.CreateDMChannelAsync().ConfigureAwait(false); - if (channel == null) + break; + + // 服务器封禁用户 + case ("GROUP", "added_block_list"): { - await UnknownChannelAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); - return; + await _gatewayLogger.DebugAsync("Received Event (added_block_list)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var guild = State.GetGuild(gatewayEvent.TargetId); + if (guild != null) + { + SocketUser operatorUser = guild.GetUser(data.OperatorUserId) + ?? (SocketUser)SocketUnknownUser.Create(this, State, data.OperatorUserId); + var bannedUsers = data.UserIds.Select(id => guild.GetUser(id) + ?? (SocketUser)SocketUnknownUser.Create(this, State, id)) + .ToReadOnlyCollection(() => data.UserIds.Length); + await TimedInvokeAsync(_userBannedEvent, nameof(UserBanned), bannedUsers, operatorUser, guild).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } } - IMessage message = await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false); - await TimedInvokeAsync(_directMessageButtonClickedEvent, nameof(DirectMessageButtonClicked), data.Value, user, message, channel).ConfigureAwait(false); - } + break; + + // 服务器取消封禁用户 + case ("GROUP", "deleted_block_list"): + { + await _gatewayLogger.DebugAsync("Received Event (deleted_block_list)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var guild = State.GetGuild(gatewayEvent.TargetId); + if (guild != null) + { + SocketUser operatorUser = guild.GetUser(data.OperatorUserId) + ?? (SocketUser)SocketUnknownUser.Create(this, State, data.OperatorUserId); + var unbannedUsers = data.UserIds.Select(id => guild.GetUser(id) + ?? (SocketUser)SocketUnknownUser.Create(this, State, id)) + .ToReadOnlyCollection(() => data.UserIds.Length); + await TimedInvokeAsync(_userUnbannedEvent, nameof(UserUnbanned), unbannedUsers, operatorUser, guild).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } + } + break; + + #endregion + + #region Users + + // 用户加入语音频道 + case ("GROUP", "joined_channel"): + { + await _gatewayLogger.DebugAsync("Received Event (joined_channel)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var guild = State.GetGuild(gatewayEvent.TargetId); + if (guild != null) + { + var channel = GetChannel(data.ChannelId) as SocketVoiceChannel; + + if (channel == null) + { + await UnknownChannelAsync(extraData.Type, data.ChannelId).ConfigureAwait(false); + return; + } + + var user = guild.GetUser(data.UserId) + ?? SocketUnknownUser.Create(this, State, data.UserId) as SocketUser; + guild.AddOrUpdateVoiceState(user.Id, channel.Id); + + await TimedInvokeAsync(_userConnectedEvent, nameof(UserConnected), user, channel, guild, data.At).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } + } + break; + + // 用户退出语音频道 + case ("GROUP", "exited_channel"): + { + await _gatewayLogger.DebugAsync("Received Event (exited_channel)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + var guild = State.GetGuild(gatewayEvent.TargetId); + if (guild != null) + { + var channel = GetChannel(data.ChannelId) as SocketVoiceChannel; + + if (channel == null) + { + await UnknownChannelAsync(extraData.Type, data.ChannelId).ConfigureAwait(false); + return; + } + + var user = guild.GetUser(data.UserId) + ?? SocketUnknownUser.Create(this, State, data.UserId) as SocketUser; + guild.AddOrUpdateVoiceState(user.Id, voiceChannelId: null); + + await TimedInvokeAsync(_userDisconnectedEvent, nameof(UserDisconnected), user, channel, guild, data.At).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } + } + break; + + // 用户信息更新 + case ("PERSON", "user_updated"): + { + await _gatewayLogger.DebugAsync("Received Event (user_updated)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + if (data.UserId == CurrentUser.Id) + { + var before = CurrentUser.Clone(); + CurrentUser.Update(State, data); + await TimedInvokeAsync(_selfUpdatedEvent, nameof(CurrentUserUpdated), before, CurrentUser).ConfigureAwait(false); + } + else + { + SocketUser user = GetUser(data.UserId); + var before = user.Clone(); + user.Update(State, data); + await TimedInvokeAsync(_userUpdatedEvent, nameof(UserUpdated), before, CurrentUser).ConfigureAwait(false); + } + } + break; + + // 自己新加入服务器 + case ("PERSON", "self_joined_guild"): + { + await _gatewayLogger.DebugAsync("Received Event (self_joined_guild)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + + var task = new Func>(async id => + { + int maxRetryTime = 5; + while (true) + { + try + { return await ApiClient.GetGuildAsync(id).ConfigureAwait(false); } + catch (HttpException ex) when (ex.HttpCode == HttpStatusCode.Forbidden) { if (--maxRetryTime == 0) throw; } + await Task.Delay(500).ConfigureAwait(false); + } + }); + + ExtendedGuild model = await task(data.GuildId).ConfigureAwait(false); + var guild = AddGuild(model, State); + guild.Update(State, model); + await TimedInvokeAsync(_joinedGuildEvent, nameof(JoinedGuild), guild).ConfigureAwait(false); + await GuildAvailableAsync(guild).ConfigureAwait(false); + } + break; + + // 自己退出服务器 + case ("PERSON", "self_exited_guild"): + { + await _gatewayLogger.DebugAsync("Received Event (self_exited_guild)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + + var guild = RemoveGuild(data.GuildId); + if (guild != null) + { + await GuildUnavailableAsync(guild).ConfigureAwait(false); + await TimedInvokeAsync(_leftGuildEvent, nameof(LeftGuild), guild).ConfigureAwait(false); + ((IDisposable)guild).Dispose(); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } + } + break; + + #endregion + + #region Interactions + + // Card 消息中的 Button 点击事件 + case ("PERSON", "message_btn_click"): + { + await _gatewayLogger.DebugAsync("Received Event (message_btn_click)").ConfigureAwait(false); + var data = ((JsonElement)extraData.Body).Deserialize(_serializerOptions); + if (data.GuildId.HasValue) + { + SocketTextChannel channel = GetChannel(data.ChannelId) as SocketTextChannel; + SocketGuild guild = GetGuild(data.GuildId.Value); + if (guild != null) + { + if (channel == null) + { + await UnknownChannelAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } + SocketUser user = channel.GetUser(data.UserId) + ?? SocketUnknownUser.Create(this, State, data.UserId) as SocketUser; + IMessage msg = await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false); + await TimedInvokeAsync(_messageButtonClickedEvent, nameof(MessageButtonClicked), data.Value, user, msg, channel, guild).ConfigureAwait(false); + } + else + { + await UnknownGuildAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } + } + else + { + SocketUser user = GetUser(data.UserId) + ?? SocketUnknownUser.Create(this, State, data.UserId); + SocketDMChannel channel = await user.CreateDMChannelAsync().ConfigureAwait(false); + if (channel == null) + { + await UnknownChannelAsync(extraData.Type, gatewayEvent.TargetId).ConfigureAwait(false); + return; + } + IMessage message = await channel.GetMessageAsync(data.MessageId).ConfigureAwait(false); + await TimedInvokeAsync(_directMessageButtonClickedEvent, nameof(DirectMessageButtonClicked), data.Value, user, message, channel).ConfigureAwait(false); + } + } + break; + + #endregion + + default: + await _gatewayLogger.WarningAsync($"Unknown SystemEventType ({extraData.Type})") + .ConfigureAwait(false); + break; } - break; - - #endregion - - default: - await _gatewayLogger.WarningAsync($"Unknown SystemEventType ({extraData.Type})") - .ConfigureAwait(false); - break; } - } break; default: await _gatewayLogger.WarningAsync($"Unknown Event Type ({gatewayEvent.Type})") @@ -1468,161 +1470,161 @@ await _gatewayLogger.WarningAsync($"Unknown Event Type ({gatewayEvent.Type})") break; case GatewaySocketFrameType.Hello: - { - // Process Hello - await _gatewayLogger.DebugAsync("Received Hello").ConfigureAwait(false); - try - { - GatewayHelloPayload gatewayHelloPayload = - ((JsonElement) payload).Deserialize(_serializerOptions); - _sessionId = gatewayHelloPayload?.SessionId; - _heartbeatTask = RunHeartbeatAsync(_connection.CancelToken); - } - catch (Exception ex) - { - _connection.CriticalError(new Exception("Processing Hello failed", ex)); - return; - } - - // Get current user - try - { - SelfUser selfUser = await ApiClient.GetSelfUserAsync().ConfigureAwait(false); - var currentUser = SocketSelfUser.Create(this, State, selfUser); - Rest.CreateRestSelfUser(selfUser); - ApiClient.CurrentUserId = currentUser.Id; - Rest.CurrentUser = RestSelfUser.Create(this, selfUser); - CurrentUser = currentUser; - } - catch (Exception ex) { - _connection.CriticalError(new Exception("Processing SelfUser failed", ex)); - return; - } - - // Download guild data - try - { - var guilds = await ApiClient.ListGuildsAsync().ConfigureAwait(false); - var state = new ClientState(guilds.Count, 0); - int unavailableGuilds = 0; - foreach (RichGuild guild in guilds) + // Process Hello + await _gatewayLogger.DebugAsync("Received Hello").ConfigureAwait(false); + try { - var model = guild; - var socketGuild = AddGuild(model, state); - if (!socketGuild.IsAvailable) - unavailableGuilds++; - else - await GuildAvailableAsync(socketGuild).ConfigureAwait(false); + GatewayHelloPayload gatewayHelloPayload = + ((JsonElement)payload).Deserialize(_serializerOptions); + _sessionId = gatewayHelloPayload?.SessionId; + _heartbeatTask = RunHeartbeatAsync(_connection.CancelToken); } - _unavailableGuildCount = unavailableGuilds; - State = state; - } - catch (Exception ex) - { - _connection.CriticalError(new Exception("Processing Guilds failed", ex)); - return; - } - - // // Download guild data - // try - // { - // var guilds = (await ApiClient.GetGuildsAsync().FlattenAsync().ConfigureAwait(false)).ToList(); - // var state = new ClientState(guilds.Count, 0); - // int unavailableGuilds = 0; - // foreach (Guild guild in guilds) - // { - // var model = guild; - // var socketGuild = AddGuild(model, state); - // if (!socketGuild.IsAvailable) - // unavailableGuilds++; - // else - // await GuildAvailableAsync(socketGuild).ConfigureAwait(false); - // } - // _unavailableGuildCount = unavailableGuilds; - // State = state; - // } - // catch (Exception ex) - // { - // _connection.CriticalError(new Exception("Processing Guilds failed", ex)); - // return; - // } - - _lastGuildAvailableTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - _guildDownloadTask = WaitForGuildsAsync(_connection.CancelToken, _gatewayLogger) - .ContinueWith(async task => + catch (Exception ex) { - if (task.IsFaulted) + _connection.CriticalError(new Exception("Processing Hello failed", ex)); + return; + } + + // Get current user + try + { + SelfUser selfUser = await ApiClient.GetSelfUserAsync().ConfigureAwait(false); + var currentUser = SocketSelfUser.Create(this, State, selfUser); + Rest.CreateRestSelfUser(selfUser); + ApiClient.CurrentUserId = currentUser.Id; + Rest.CurrentUser = RestSelfUser.Create(this, selfUser); + CurrentUser = currentUser; + } + catch (Exception ex) + { + _connection.CriticalError(new Exception("Processing SelfUser failed", ex)); + return; + } + + // Download guild data + try + { + var guilds = await ApiClient.ListGuildsAsync().ConfigureAwait(false); + var state = new ClientState(guilds.Count, 0); + int unavailableGuilds = 0; + foreach (RichGuild guild in guilds) { - _connection.Error(task.Exception); - return; + var model = guild; + var socketGuild = AddGuild(model, state); + if (!socketGuild.IsAvailable) + unavailableGuilds++; + else + await GuildAvailableAsync(socketGuild).ConfigureAwait(false); } - else if (_connection.CancelToken.IsCancellationRequested) - return; - - // Download user list if enabled - if (BaseConfig.AlwaysDownloadUsers) - _ = DownloadUsersAsync(Guilds.Where(x => x.IsAvailable && x.HasAllMembers is not true)); - if (BaseConfig.AlwaysDownloadVoiceStates) - _ = DownloadVoiceStatesAsync(Guilds.Where(x => x.IsAvailable)); - if (BaseConfig.AlwaysDownloadBoostSubscriptions) - _ = DownloadBoostSubscriptionsAsync(Guilds.Where(x => x.IsAvailable)); - - await TimedInvokeAsync(_readyEvent, nameof(Ready)).ConfigureAwait(false); - await _gatewayLogger.InfoAsync("Ready").ConfigureAwait(false); - }); - - _ = _connection.CompleteAsync(); - - } + _unavailableGuildCount = unavailableGuilds; + State = state; + } + catch (Exception ex) + { + _connection.CriticalError(new Exception("Processing Guilds failed", ex)); + return; + } + + // // Download guild data + // try + // { + // var guilds = (await ApiClient.GetGuildsAsync().FlattenAsync().ConfigureAwait(false)).ToList(); + // var state = new ClientState(guilds.Count, 0); + // int unavailableGuilds = 0; + // foreach (Guild guild in guilds) + // { + // var model = guild; + // var socketGuild = AddGuild(model, state); + // if (!socketGuild.IsAvailable) + // unavailableGuilds++; + // else + // await GuildAvailableAsync(socketGuild).ConfigureAwait(false); + // } + // _unavailableGuildCount = unavailableGuilds; + // State = state; + // } + // catch (Exception ex) + // { + // _connection.CriticalError(new Exception("Processing Guilds failed", ex)); + // return; + // } + + _lastGuildAvailableTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + _guildDownloadTask = WaitForGuildsAsync(_connection.CancelToken, _gatewayLogger) + .ContinueWith(async task => + { + if (task.IsFaulted) + { + _connection.Error(task.Exception); + return; + } + else if (_connection.CancelToken.IsCancellationRequested) + return; + + // Download user list if enabled + if (BaseConfig.AlwaysDownloadUsers) + _ = DownloadUsersAsync(Guilds.Where(x => x.IsAvailable && x.HasAllMembers is not true)); + if (BaseConfig.AlwaysDownloadVoiceStates) + _ = DownloadVoiceStatesAsync(Guilds.Where(x => x.IsAvailable)); + if (BaseConfig.AlwaysDownloadBoostSubscriptions) + _ = DownloadBoostSubscriptionsAsync(Guilds.Where(x => x.IsAvailable)); + + await TimedInvokeAsync(_readyEvent, nameof(Ready)).ConfigureAwait(false); + await _gatewayLogger.InfoAsync("Ready").ConfigureAwait(false); + }); + + _ = _connection.CompleteAsync(); + + } break; case GatewaySocketFrameType.Pong: - { - await _gatewayLogger.DebugAsync("Received Pong").ConfigureAwait(false); - if (_heartbeatTimes.TryDequeue(out long time)) { - int latency = (int) (DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - time); - int before = Latency; - Latency = latency; + await _gatewayLogger.DebugAsync("Received Pong").ConfigureAwait(false); + if (_heartbeatTimes.TryDequeue(out long time)) + { + int latency = (int)(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - time); + int before = Latency; + Latency = latency; - await TimedInvokeAsync(_latencyUpdatedEvent, nameof(LatencyUpdated), before, latency) - .ConfigureAwait(false); + await TimedInvokeAsync(_latencyUpdatedEvent, nameof(LatencyUpdated), before, latency) + .ConfigureAwait(false); + } } - } break; case GatewaySocketFrameType.Reconnect: - { - await _gatewayLogger.DebugAsync("Received Reconnect").ConfigureAwait(false); - GatewayReconnectPayload gatewayReconnectPayload = - ((JsonElement) payload).Deserialize(_serializerOptions); - if (gatewayReconnectPayload?.Code is KookErrorCode.MissingResumeArgument - or KookErrorCode.SessionExpired - or KookErrorCode.InvalidSequenceNumber) { - _sessionId = null; - _lastSeq = 0; + await _gatewayLogger.DebugAsync("Received Reconnect").ConfigureAwait(false); + GatewayReconnectPayload gatewayReconnectPayload = + ((JsonElement)payload).Deserialize(_serializerOptions); + if (gatewayReconnectPayload?.Code is KookErrorCode.MissingResumeArgument + or KookErrorCode.SessionExpired + or KookErrorCode.InvalidSequenceNumber) + { + _sessionId = null; + _lastSeq = 0; + } + _connection.Error(new GatewayReconnectException($"Server requested a reconnect, resuming session failed" + + $"{(string.IsNullOrWhiteSpace(gatewayReconnectPayload?.Message) ? string.Empty : $": {gatewayReconnectPayload.Message}")}")); } - _connection.Error(new GatewayReconnectException($"Server requested a reconnect, resuming session failed" + - $"{(string.IsNullOrWhiteSpace(gatewayReconnectPayload?.Message) ? string.Empty : $": {gatewayReconnectPayload.Message}")}")); - } break; case GatewaySocketFrameType.ResumeAck: - { - await _gatewayLogger.DebugAsync("Received ResumeAck").ConfigureAwait(false); - _ = _connection.CompleteAsync(); - - //Notify the client that these guilds are available again - foreach (var guild in State.Guilds) { - if (guild.IsAvailable) - await GuildAvailableAsync(guild).ConfigureAwait(false); - } + await _gatewayLogger.DebugAsync("Received ResumeAck").ConfigureAwait(false); + _ = _connection.CompleteAsync(); - await _gatewayLogger.InfoAsync("Resumed previous session").ConfigureAwait(false); - } + //Notify the client that these guilds are available again + foreach (var guild in State.Guilds) + { + if (guild.IsAvailable) + await GuildAvailableAsync(guild).ConfigureAwait(false); + } + + await _gatewayLogger.InfoAsync("Resumed previous session").ConfigureAwait(false); + } break; default: @@ -1713,7 +1715,7 @@ private async Task WaitForGuildsAsync(CancellationToken cancelToken, Logger logg await logger.ErrorAsync("GuildDownloader Errored", ex).ConfigureAwait(false); } } - + internal SocketGuild AddGuild(API.Guild model, ClientState state) { var guild = SocketGuild.Create(this, state, model); @@ -1744,7 +1746,7 @@ internal SocketDMChannel CreateDMChannel(Guid chatCode, SocketUser user, ClientS { return new SocketDMChannel(this, chatCode, user); } - + private async Task GuildAvailableAsync(SocketGuild guild) { if (!guild.IsConnected) @@ -1761,7 +1763,7 @@ private async Task GuildUnavailableAsync(SocketGuild guild) await TimedInvokeAsync(_guildUnavailableEvent, nameof(GuildUnavailable), guild).ConfigureAwait(false); } } - + private async Task TimedInvokeAsync(AsyncEvent> eventHandler, string name) { if (eventHandler.HasSubscribers) @@ -1853,7 +1855,7 @@ await _gatewayLogger.WarningAsync($"A {name} handler has thrown an unhandled exc .ConfigureAwait(false); } } - + private async Task UnknownChannelUserAsync(string evnt, ulong userId, Guid chatCode) { string details = $"{evnt} User={userId} ChatCode={chatCode}"; @@ -1929,7 +1931,7 @@ Task> IKookClient.GetGuildsAsync(CacheMode mode, Req /// Task IKookClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult(GetGuild(id)); - + /// async Task IKookClient.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) { @@ -1949,6 +1951,6 @@ async Task IKookClient.GetDMChannelAsync(Guid chatCode, CacheMode mo /// async Task> IKookClient.GetDMChannelsAsync(CacheMode mode, RequestOptions options) => mode == CacheMode.AllowDownload ? await GetDMChannelsAsync(options).ConfigureAwait(false) : DMChannels; - + #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/KookSocketConfig.cs b/src/Kook.Net.WebSocket/KookSocketConfig.cs index 68a51deb..959dc9a8 100644 --- a/src/Kook.Net.WebSocket/KookSocketConfig.cs +++ b/src/Kook.Net.WebSocket/KookSocketConfig.cs @@ -144,4 +144,4 @@ public KookSocketConfig() } internal KookSocketConfig Clone() => MemberwiseClone() as KookSocketConfig; -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/KookSocketRestClient.cs b/src/Kook.Net.WebSocket/KookSocketRestClient.cs index 778a8bb7..c532eb1d 100644 --- a/src/Kook.Net.WebSocket/KookSocketRestClient.cs +++ b/src/Kook.Net.WebSocket/KookSocketRestClient.cs @@ -5,7 +5,7 @@ namespace Kook.WebSocket; public class KookSocketRestClient : KookRestClient { internal KookSocketRestClient(KookRestConfig config, API.KookRestApiClient api) : base(config, api) { } - + public new Task LoginAsync(TokenType tokenType, string token, bool validateToken = true) => throw new NotSupportedException("The Socket REST wrapper cannot be used to log in or out."); internal override Task LoginInternalAsync(TokenType tokenType, string token, bool validateToken) @@ -14,4 +14,4 @@ internal override Task LoginInternalAsync(TokenType tokenType, string token, boo => throw new NotSupportedException("The Socket REST wrapper cannot be used to log in or out."); internal override Task LogoutInternalAsync() => throw new NotSupportedException("The Socket REST wrapper cannot be used to log in or out."); -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/KookVoiceAPIClient.cs b/src/Kook.Net.WebSocket/KookVoiceAPIClient.cs index 65149635..a1e6f2f3 100644 --- a/src/Kook.Net.WebSocket/KookVoiceAPIClient.cs +++ b/src/Kook.Net.WebSocket/KookVoiceAPIClient.cs @@ -54,14 +54,14 @@ public event Func ReceivedEvent remove => _receivedEvent.Remove(value); } private readonly AsyncEvent> _receivedEvent = new AsyncEvent>(); - public event Func ReceivedPacket - { + public event Func ReceivedPacket + { add => _receivedPacketEvent.Add(value); remove => _receivedPacketEvent.Remove(value); } private readonly AsyncEvent> _receivedPacketEvent = new AsyncEvent>(); - public event Func Disconnected - { + public event Func Disconnected + { add => _disconnectedEvent.Add(value); remove => _disconnectedEvent.Remove(value); } @@ -81,7 +81,7 @@ public event Func Disconnected public ushort UdpPort => _udp.Port; - internal KookVoiceAPIClient(ulong guildId, WebSocketProvider webSocketProvider, + internal KookVoiceAPIClient(ulong guildId, WebSocketProvider webSocketProvider, UdpSocketProvider udpSocketProvider, JsonSerializerOptions serializerOptions = null) { GuildId = guildId; @@ -196,7 +196,7 @@ public async Task SendProduceRequestAsync(Guid transportId, uint ssrc, RequestOp PeerId = string.Empty, RTPParameters = new RTPParameters { - Codecs = new [] + Codecs = new[] { new Codec() { @@ -210,7 +210,7 @@ public async Task SendProduceRequestAsync(Guid transportId, uint ssrc, RequestOp PayloadType = 100 } }, - Encodings = new [] + Encodings = new[] { new API.Voice.Encoding { @@ -323,17 +323,17 @@ public void SetUdpEndpoint(string ip, int port) #region Helpers private static double ToMilliseconds(Stopwatch stopwatch) => Math.Round((double)stopwatch.ElapsedTicks / (double)Stopwatch.Frequency * 1000.0, 2); - + private string SerializeJson(object payload) { - return payload is null - ? string.Empty + return payload is null + ? string.Empty : JsonSerializer.Serialize(payload, _serializerOptions); } - + private T DeserializeJson(Stream jsonStream) { return JsonSerializer.Deserialize(jsonStream, _serializerOptions); } #endregion -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Net/Converters/GatewaySocketFrameTypeConverter.cs b/src/Kook.Net.WebSocket/Net/Converters/GatewaySocketFrameTypeConverter.cs index d80e928b..5b9c3c53 100644 --- a/src/Kook.Net.WebSocket/Net/Converters/GatewaySocketFrameTypeConverter.cs +++ b/src/Kook.Net.WebSocket/Net/Converters/GatewaySocketFrameTypeConverter.cs @@ -1,6 +1,6 @@ +using Kook.API.Gateway; using System.Text.Json; using System.Text.Json.Serialization; -using Kook.API.Gateway; namespace Kook.Net.Converters; @@ -8,11 +8,11 @@ internal class GatewaySocketFrameTypeConverter : JsonConverter { public override MessageType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return (MessageType) reader.GetInt32(); + return (MessageType)reader.GetInt32(); } public override void Write(Utf8JsonWriter writer, MessageType value, JsonSerializerOptions options) { - writer.WriteNumberValue((int) value); + writer.WriteNumberValue((int)value); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Net/Converters/VoiceSocketFrameTypeConverter.cs b/src/Kook.Net.WebSocket/Net/Converters/VoiceSocketFrameTypeConverter.cs index 6a3c9b36..6a5830d9 100644 --- a/src/Kook.Net.WebSocket/Net/Converters/VoiceSocketFrameTypeConverter.cs +++ b/src/Kook.Net.WebSocket/Net/Converters/VoiceSocketFrameTypeConverter.cs @@ -1,6 +1,6 @@ +using Kook.API.Voice; using System.Text.Json; using System.Text.Json.Serialization; -using Kook.API.Voice; namespace Kook.Net.Converters; @@ -25,4 +25,4 @@ public override void Write(Utf8JsonWriter writer, VoiceSocketFrameType value, Js : method.ToLower(); writer.WriteStringValue(method); } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Net/DefaultUdpSocket.cs b/src/Kook.Net.WebSocket/Net/DefaultUdpSocket.cs index 154cbeee..1f4b0909 100644 --- a/src/Kook.Net.WebSocket/Net/DefaultUdpSocket.cs +++ b/src/Kook.Net.WebSocket/Net/DefaultUdpSocket.cs @@ -87,7 +87,8 @@ public async Task StopAsync() } public async Task StopInternalAsync(bool isDisposing = false) { - try { _stopCancelTokenSource.Cancel(false); } + try + { _stopCancelTokenSource.Cancel(false); } catch { // ignored @@ -98,7 +99,8 @@ public async Task StopInternalAsync(bool isDisposing = false) if (_udp != null) { - try { _udp.Dispose(); } + try + { _udp.Dispose(); } catch { // ignored @@ -154,4 +156,4 @@ private async Task RunAsync(CancellationToken cancelToken) await ReceivedDatagram(result.Buffer, 0, result.Buffer.Length).ConfigureAwait(false); } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Net/DefaultUdpSocketProvider.cs b/src/Kook.Net.WebSocket/Net/DefaultUdpSocketProvider.cs index 357042be..4022fbc2 100644 --- a/src/Kook.Net.WebSocket/Net/DefaultUdpSocketProvider.cs +++ b/src/Kook.Net.WebSocket/Net/DefaultUdpSocketProvider.cs @@ -4,7 +4,7 @@ namespace Kook.Net.Udp; public static class DefaultUdpSocketProvider { - public static readonly UdpSocketProvider Instance = () => + public static readonly UdpSocketProvider Instance = () => { try { @@ -15,4 +15,4 @@ public static class DefaultUdpSocketProvider throw new PlatformNotSupportedException("The default UdpSocketProvider is not supported on this platform.", ex); } }; -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Net/DefaultWebSocketClient.cs b/src/Kook.Net.WebSocket/Net/DefaultWebSocketClient.cs index eed121e8..587b4787 100644 --- a/src/Kook.Net.WebSocket/Net/DefaultWebSocketClient.cs +++ b/src/Kook.Net.WebSocket/Net/DefaultWebSocketClient.cs @@ -105,7 +105,8 @@ private async Task DisconnectInternalAsync(int closeCode = 1000, bool isDisposin { _isDisconnecting = true; - try { _disconnectTokenSource.Cancel(false); } + try + { _disconnectTokenSource.Cancel(false); } catch { // ignored @@ -116,13 +117,15 @@ private async Task DisconnectInternalAsync(int closeCode = 1000, bool isDisposin if (!isDisposing) { var status = (WebSocketCloseStatus)closeCode; - try { await _client.CloseOutputAsync(status, "", new CancellationToken()); } + try + { await _client.CloseOutputAsync(status, "", new CancellationToken()); } catch { // ignored } } - try { _client.Dispose(); } + try + { _client.Dispose(); } catch { // ignored @@ -180,7 +183,8 @@ public async Task SendAsync(byte[] data, int index, int count, bool isText) } try { - if (_client == null) return; + if (_client == null) + return; int frameCount = (int)Math.Ceiling((double)count / SendChunkSize); @@ -227,7 +231,8 @@ private async Task RunAsync(CancellationToken cancelToken) stream.Write(buffer.Array, 0, socketResult.Count); do { - if (cancelToken.IsCancellationRequested) return; + if (cancelToken.IsCancellationRequested) + return; socketResult = await _client.ReceiveAsync(buffer, cancelToken).ConfigureAwait(false); stream.Write(buffer.Array, 0, socketResult.Count); } @@ -270,4 +275,4 @@ private async Task RunAsync(CancellationToken cancelToken) var _ = OnClosed(ex); } } -} \ No newline at end of file +} diff --git a/src/Kook.Net.WebSocket/Net/DefaultWebSocketClientProvider.cs b/src/Kook.Net.WebSocket/Net/DefaultWebSocketClientProvider.cs index 567219ae..faeb0737 100644 --- a/src/Kook.Net.WebSocket/Net/DefaultWebSocketClientProvider.cs +++ b/src/Kook.Net.WebSocket/Net/DefaultWebSocketClientProvider.cs @@ -21,4 +21,4 @@ public static WebSocketProvider Create(IWebProxy proxy = null) } }; } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Integration/ChannelTests.cs b/test/Kook.Net.Tests.Integration/ChannelTests.cs index 5b051516..a32a929d 100644 --- a/test/Kook.Net.Tests.Integration/ChannelTests.cs +++ b/test/Kook.Net.Tests.Integration/ChannelTests.cs @@ -1,10 +1,10 @@ +using FluentAssertions; +using Kook.Rest; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using FluentAssertions; -using Kook.Rest; using Xunit; using Xunit.Abstractions; @@ -164,7 +164,7 @@ async Task CheckAsync(INestedChannel channel, ICategoryChannel cat) public async Task MiscAsync() { ICategoryChannel category = await _guild.CreateCategoryChannelAsync("CATEGORY"); - RestTextChannel channel = await _guild.CreateTextChannelAsync("TEXT", + RestTextChannel channel = await _guild.CreateTextChannelAsync("TEXT", p => p.CategoryId = category.Id) as RestTextChannel; try { @@ -174,15 +174,15 @@ public async Task MiscAsync() Assert.NotNull(channel); Assert.NotNull(selfUser); Assert.NotNull(role); - + // set the category await channel.ModifyAsync(x => x.CategoryId = category.Id); - + // check that the creator is myself Assert.Equal(selfUser.Id, channel.CreatorId); IUser creator = await channel.GetCreatorAsync(); Assert.Equal(selfUser.Id, creator.Id); - + // check permission overwrites await channel.AddPermissionOverwriteAsync(selfUser); Assert.Single(channel.UserPermissionOverwrites); @@ -195,7 +195,7 @@ await channel.ModifyPermissionOverwriteAsync(selfUser, permissions => permission Assert.Equal(PermValue.Inherit, userPermissionOverwrite.Permissions.AttachFiles); await channel.RemovePermissionOverwriteAsync(selfUser); Assert.Empty(channel.UserPermissionOverwrites); - + await channel.AddPermissionOverwriteAsync(role); Assert.Single(channel.RolePermissionOverwrites.Where(overwrite => overwrite.Target > 0)); await channel.ModifyPermissionOverwriteAsync(role, permissions => permissions @@ -207,7 +207,7 @@ await channel.ModifyPermissionOverwriteAsync(role, permissions => permissions Assert.Equal(PermValue.Inherit, rolePermissionOverwrite.Permissions.AttachFiles); await channel.RemovePermissionOverwriteAsync(role); Assert.Empty(channel.RolePermissionOverwrites.Where(overwrite => overwrite.Target > 0)); - + // check permission sync Assert.True(channel.IsPermissionSynced); await channel.AddPermissionOverwriteAsync(role); @@ -216,7 +216,7 @@ await channel.ModifyPermissionOverwriteAsync(role, permissions => permissions await channel.SyncPermissionsAsync(); await channel.UpdateAsync(); Assert.True(channel.IsPermissionSynced); - + // check invites IInvite invite = await channel.CreateInviteAsync(InviteMaxAge._86400, InviteMaxUses._50); Assert.NotNull(invite); @@ -230,4 +230,4 @@ await channel.ModifyPermissionOverwriteAsync(role, permissions => permissions await category.DeleteAsync(); } } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Integration/Fixtures/KookRestClientFixture.cs b/test/Kook.Net.Tests.Integration/Fixtures/KookRestClientFixture.cs index 232a9538..79a1710c 100644 --- a/test/Kook.Net.Tests.Integration/Fixtures/KookRestClientFixture.cs +++ b/test/Kook.Net.Tests.Integration/Fixtures/KookRestClientFixture.cs @@ -30,4 +30,4 @@ public void Dispose() Client.LogoutAsync().GetAwaiter().GetResult(); Client.Dispose(); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Integration/Fixtures/RestChannelFixture.cs b/test/Kook.Net.Tests.Integration/Fixtures/RestChannelFixture.cs index 0a50a488..9735828c 100644 --- a/test/Kook.Net.Tests.Integration/Fixtures/RestChannelFixture.cs +++ b/test/Kook.Net.Tests.Integration/Fixtures/RestChannelFixture.cs @@ -1,8 +1,8 @@ using Kook.Rest; using System; using System.Collections.Generic; -using System.Text; using System.Linq; +using System.Text; using System.Threading.Tasks; namespace Kook; @@ -26,4 +26,4 @@ public RestChannelFixture() : base() TextChannel.DeleteAsync().GetAwaiter().GetResult(); base.Dispose(); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Integration/Fixtures/RestGuildFixture.cs b/test/Kook.Net.Tests.Integration/Fixtures/RestGuildFixture.cs index 71de76ce..8a06af74 100644 --- a/test/Kook.Net.Tests.Integration/Fixtures/RestGuildFixture.cs +++ b/test/Kook.Net.Tests.Integration/Fixtures/RestGuildFixture.cs @@ -1,8 +1,8 @@ using Kook.Rest; using System; using System.Collections.Generic; -using System.Text; using System.Linq; +using System.Text; namespace Kook; @@ -48,4 +48,4 @@ private void RemoveAllRoles() role.DeleteAsync().GetAwaiter().GetResult(); } } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Integration/GuildTests.cs b/test/Kook.Net.Tests.Integration/GuildTests.cs index 310ef2b0..1109ac92 100644 --- a/test/Kook.Net.Tests.Integration/GuildTests.cs +++ b/test/Kook.Net.Tests.Integration/GuildTests.cs @@ -1,7 +1,7 @@ +using FluentAssertions; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using FluentAssertions; using Xunit; using Xunit.Abstractions; @@ -68,4 +68,4 @@ public async Task ModifyNicknameAsync() currentUser.DisplayName.Should().Be(currentUser.Username); (await _guild.GetCurrentUserAsync()).DisplayName.Should().Be(currentUser.Username); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Integration/KookRestApiClientTests.cs b/test/Kook.Net.Tests.Integration/KookRestApiClientTests.cs index 1681aa2d..cc7a60cf 100644 --- a/test/Kook.Net.Tests.Integration/KookRestApiClientTests.cs +++ b/test/Kook.Net.Tests.Integration/KookRestApiClientTests.cs @@ -1,8 +1,8 @@ -using Kook.API; +using FluentAssertions; +using Kook.API; using Kook.API.Rest; using Kook.Net; using Kook.Rest; -using FluentAssertions; using System; using System.Collections.Generic; using System.IO; @@ -34,10 +34,10 @@ public ValueTask DisposeAsync() [Fact] public async Task CreateAsset_WithMaximumSize_DontThrowsException() { - ulong fileSize = (ulong) (30 * Math.Pow(2, 20)); + ulong fileSize = (ulong)(30 * Math.Pow(2, 20)); using MemoryStream stream = new(new byte[fileSize]); CreateAssetResponse response = - await _apiClient.CreateAssetAsync(new CreateAssetParams {File = stream, FileName = "test.file"}); + await _apiClient.CreateAssetAsync(new CreateAssetParams { File = stream, FileName = "test.file" }); response.Url.Should().NotBeNullOrWhiteSpace(); } @@ -46,9 +46,9 @@ public async Task CreateAsset_WithOverSize_ThrowsException() { Func upload = async () => { - ulong fileSize = (ulong) (30 * Math.Pow(2, 20)) + 1; + ulong fileSize = (ulong)(30 * Math.Pow(2, 20)) + 1; using MemoryStream stream = new(new byte[fileSize]); - await _apiClient.CreateAssetAsync(new CreateAssetParams {File = stream, FileName = "test.file"}); + await _apiClient.CreateAssetAsync(new CreateAssetParams { File = stream, FileName = "test.file" }); }; await upload.Should().ThrowExactlyAsync() diff --git a/test/Kook.Net.Tests.Integration/MessageTests.cs b/test/Kook.Net.Tests.Integration/MessageTests.cs index 3b1f7209..ff25bf4e 100644 --- a/test/Kook.Net.Tests.Integration/MessageTests.cs +++ b/test/Kook.Net.Tests.Integration/MessageTests.cs @@ -1,8 +1,8 @@ -using System; +using Kook.Rest; +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Kook.Rest; using Xunit; using Xunit.Abstractions; @@ -15,7 +15,7 @@ namespace Kook; [Trait("Category", "Integration")] public class MessageTests : IClassFixture { - + private readonly IGuild _guild; private readonly ITextChannel _channel; private readonly IGuildUser _selfUser; @@ -142,5 +142,5 @@ public async Task ReactionsAsync() await message.DeleteAsync(); } } - -} \ No newline at end of file + +} diff --git a/test/Kook.Net.Tests.Integration/RoleTests.cs b/test/Kook.Net.Tests.Integration/RoleTests.cs index 1ee08960..e218f9d0 100644 --- a/test/Kook.Net.Tests.Integration/RoleTests.cs +++ b/test/Kook.Net.Tests.Integration/RoleTests.cs @@ -1,8 +1,8 @@ +using Kook.Rest; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Kook.Rest; using Xunit; using Xunit.Abstractions; @@ -17,7 +17,7 @@ public class RoleTests : IClassFixture { private readonly IGuild _guild; private readonly ITestOutputHelper _output; - + public RoleTests(RestGuildFixture guildFixture, ITestOutputHelper output) { _guild = guildFixture.Guild; @@ -31,7 +31,7 @@ private Task LogAsync(LogMessage message) _output.WriteLine(message.ToString()); return Task.CompletedTask; } - + [Fact] public async Task ModifyRoleAsync() { @@ -88,5 +88,5 @@ public async Task AddRemoveRoleAsync() await role.DeleteAsync(); } } - -} \ No newline at end of file + +} diff --git a/test/Kook.Net.Tests.Unit/CardBuilderTests.cs b/test/Kook.Net.Tests.Unit/CardBuilderTests.cs index fa1a11f6..21501645 100644 --- a/test/Kook.Net.Tests.Unit/CardBuilderTests.cs +++ b/test/Kook.Net.Tests.Unit/CardBuilderTests.cs @@ -24,7 +24,7 @@ public void Constructor() .WithSize(CardSize.Small) .WithColor(Color.Blue) .AddModule(b => - b.WithText(t => + b.WithText(t => t.WithContent("text"))); Assert.Equal(CardTheme.Info, builder.Theme); Assert.Equal(CardTheme.Info, builder.Build().Theme); @@ -32,8 +32,8 @@ public void Constructor() Assert.Equal(CardSize.Small, builder.Build().Size); Assert.Equal(Color.Blue, builder.Color); Assert.Equal(Color.Blue, builder.Build().Color); - Assert.Equal("text", ((KMarkdownElementBuilder) ((SectionModuleBuilder) builder.Modules[0]).Text).Content); - Assert.Equal("text", ((KMarkdownElement) ((SectionModule) builder.Build().Modules[0]).Text).Content); + Assert.Equal("text", ((KMarkdownElementBuilder)((SectionModuleBuilder)builder.Modules[0]).Text).Content); + Assert.Equal("text", ((KMarkdownElement)((SectionModule)builder.Build().Modules[0]).Text).Content); builder = new CardBuilder { Theme = CardTheme.Danger, @@ -56,10 +56,10 @@ public void Constructor() Assert.Equal(CardSize.Large, builder.Build().Size); Assert.Equal(Color.Red, builder.Color); Assert.Equal(Color.Red, builder.Build().Color); - Assert.Equal("content", ((PlainTextElementBuilder) ((SectionModuleBuilder) builder.Modules[0]).Text).Content); - Assert.Equal("content", ((PlainTextElement) ((SectionModule) builder.Build().Modules[0]).Text).Content); + Assert.Equal("content", ((PlainTextElementBuilder)((SectionModuleBuilder)builder.Modules[0]).Text).Content); + Assert.Equal("content", ((PlainTextElement)((SectionModule)builder.Build().Modules[0]).Text).Content); } - + /// /// Tests the behavior of . /// @@ -164,4 +164,4 @@ public void AddModuleAction() } } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/ChannelPermissionsTests.cs b/test/Kook.Net.Tests.Unit/ChannelPermissionsTests.cs index 1677179c..bf2b3448 100644 --- a/test/Kook.Net.Tests.Unit/ChannelPermissionsTests.cs +++ b/test/Kook.Net.Tests.Unit/ChannelPermissionsTests.cs @@ -201,4 +201,4 @@ public void ChannelTypeResolution_Invalid() { Assert.Throws(() => ChannelPermissions.All(new MockedInvalidChannel())); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/ColorTests.cs b/test/Kook.Net.Tests.Unit/ColorTests.cs index 1fd14a34..78ce2721 100644 --- a/test/Kook.Net.Tests.Unit/ColorTests.cs +++ b/test/Kook.Net.Tests.Unit/ColorTests.cs @@ -29,10 +29,10 @@ public void Color_Default() [Fact] public void Color_FromRgb_Byte() { - Assert.Equal(0xFF0000u, new Color((byte) 255, (byte) 0, (byte) 0).RawValue); - Assert.Equal(0x00FF00u, new Color((byte) 0, (byte) 255, (byte) 0).RawValue); - Assert.Equal(0x0000FFu, new Color((byte) 0, (byte) 0, (byte) 255).RawValue); - Assert.Equal(0xFFFFFFu, new Color((byte) 255, (byte) 255, (byte) 255).RawValue); + Assert.Equal(0xFF0000u, new Color((byte)255, (byte)0, (byte)0).RawValue); + Assert.Equal(0x00FF00u, new Color((byte)0, (byte)255, (byte)0).RawValue); + Assert.Equal(0x0000FFu, new Color((byte)0, (byte)0, (byte)255).RawValue); + Assert.Equal(0xFFFFFFu, new Color((byte)255, (byte)255, (byte)255).RawValue); } [Fact] @@ -96,4 +96,4 @@ public void Color_Blue() { Assert.Equal(0x90, new Color(0xAF1390).B); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/ElementBuilderTests.cs b/test/Kook.Net.Tests.Unit/ElementBuilderTests.cs index 234d60f5..40c73085 100644 --- a/test/Kook.Net.Tests.Unit/ElementBuilderTests.cs +++ b/test/Kook.Net.Tests.Unit/ElementBuilderTests.cs @@ -10,7 +10,7 @@ public class ElementBuilderTests private const string Name = "Kook.Net"; private const string Icon = "https://kaiheila.net/logo.png"; private const string Url = "https://kaiheila.net/"; - + [Fact] public void PlainTextElementBuilder_Constructor() { @@ -50,7 +50,7 @@ IEnumerable GetValidContent() Assert.Equal(content, builder.Build().Content); } } - + [Fact] public void PlainTextElementBuilder_InvalidContent() { @@ -62,7 +62,7 @@ IEnumerable GetInvalidContent() foreach (string content in GetInvalidContent()) Assert.Throws(() => new PlainTextElementBuilder().WithContent(content)); } - + [Theory] [InlineData("")] [InlineData(" ")] @@ -73,7 +73,7 @@ public void PlainTextElementBuilder_ImplicitConversion(string content) Assert.Equal(content, builder.Content); Assert.Equal(content, builder.Build().Content); } - + [Fact] public void KMarkdownElementBuilder_Constructor() { @@ -108,7 +108,7 @@ IEnumerable GetValidContent() Assert.Equal(content, builder.Build().Content); } } - + [Fact] public void KMarkdownElementBuilder_InvalidContent() { @@ -120,7 +120,7 @@ IEnumerable GetInvalidContent() foreach (string content in GetInvalidContent()) Assert.Throws(() => new KMarkdownElementBuilder().WithContent(content)); } - + [Theory] [InlineData("")] [InlineData(" ")] @@ -131,7 +131,7 @@ public void KMarkdownElementBuilder_ImplicitConversion(string content) Assert.Equal(content, builder.Content); Assert.Equal(content, builder.Build().Content); } - + [Fact] public void ImageElementBuilder_Constructor() { @@ -147,7 +147,8 @@ public void ImageElementBuilder_Constructor() Assert.Equal(Name, builder.Alternative); Assert.Equal(Name, builder.Build().Alternative); Assert.Equal(ImageSize.Small, builder.Size); - Assert.Equal(ImageSize.Small, builder.Build().Size);; + Assert.Equal(ImageSize.Small, builder.Build().Size); + ; Assert.Equal(true, builder.Circle); Assert.Equal(true, builder.Build().Circle); builder = new ImageElementBuilder @@ -164,7 +165,8 @@ public void ImageElementBuilder_Constructor() Assert.Equal(Name, builder.Alternative); Assert.Equal(Name, builder.Build().Alternative); Assert.Equal(ImageSize.Large, builder.Size); - Assert.Equal(ImageSize.Large, builder.Build().Size);; + Assert.Equal(ImageSize.Large, builder.Build().Size); + ; Assert.Equal(false, builder.Circle); Assert.Equal(false, builder.Build().Circle); } @@ -201,7 +203,7 @@ public void ImageElementBuilder_WithSize() Assert.Equal(size, builder.Build().Size); } } - + [Theory] [InlineData(null)] [InlineData("")] @@ -224,7 +226,7 @@ public void ImageElementBuilder_InvalidUrl(string source) Assert.Equal(source, builder.Source); Assert.Throws(() => builder.Build()); } - + [Theory] [InlineData(Icon)] public void ImageElementBuilder_ImplicitConversion(string source) @@ -233,7 +235,7 @@ public void ImageElementBuilder_ImplicitConversion(string source) Assert.Equal(source, builder.Source); Assert.Equal(source, builder.Build().Source); } - + [Fact] public void ButtonElementBuilder_Constructor() { @@ -245,8 +247,8 @@ public void ButtonElementBuilder_Constructor() Assert.Equal(ElementType.Button, builder.Build().Type); Assert.Equal(ButtonTheme.Primary, builder.Theme); Assert.Equal(ButtonTheme.Primary, builder.Build().Theme); - Assert.Equal(Name, ((KMarkdownElementBuilder) builder.Text).Content); - Assert.Equal(Name, ((KMarkdownElement) builder.Build().Text).Content); + Assert.Equal(Name, ((KMarkdownElementBuilder)builder.Text).Content); + Assert.Equal(Name, ((KMarkdownElement)builder.Build().Text).Content); Assert.Equal(ButtonClickEventType.None, builder.Click); Assert.Equal(ButtonClickEventType.None, builder.Build().Click); builder = new ButtonElementBuilder @@ -260,8 +262,8 @@ public void ButtonElementBuilder_Constructor() Assert.Equal(ElementType.Button, builder.Build().Type); Assert.Equal(ButtonTheme.Success, builder.Theme); Assert.Equal(ButtonTheme.Success, builder.Build().Theme); - Assert.Equal("text", ((PlainTextElementBuilder) builder.Text).Content); - Assert.Equal("text", ((PlainTextElement) builder.Build().Text).Content); + Assert.Equal("text", ((PlainTextElementBuilder)builder.Text).Content); + Assert.Equal("text", ((PlainTextElement)builder.Build().Text).Content); Assert.Equal(ButtonClickEventType.ReturnValue, builder.Click); Assert.Equal(ButtonClickEventType.ReturnValue, builder.Build().Click); Assert.Equal("value", builder.Value); @@ -275,8 +277,8 @@ public void ButtonElementBuilder_ButtonTextAction() .WithText(b => b.WithContent("text")); Assert.IsType(builder.Text); Assert.IsType(builder.Build().Text); - Assert.Equal("text", ((PlainTextElementBuilder) builder.Text).Content); - Assert.Equal("text", ((PlainTextElement) builder.Build().Text).Content); + Assert.Equal("text", ((PlainTextElementBuilder)builder.Text).Content); + Assert.Equal("text", ((PlainTextElement)builder.Build().Text).Content); } [Fact] @@ -298,8 +300,8 @@ public void ButtonElementBuilder_ButtonTheme() public void ButtonElementBuilder_ValidText(string text) { var builder = new ButtonElementBuilder().WithText(text); - Assert.Equal(text, ((PlainTextElementBuilder) builder.Text).Content); - Assert.Equal(text, ((PlainTextElement) builder.Build().Text).Content); + Assert.Equal(text, ((PlainTextElementBuilder)builder.Text).Content); + Assert.Equal(text, ((PlainTextElement)builder.Build().Text).Content); } [Theory] @@ -346,8 +348,8 @@ public void ParagraphStructBuilder_Constructor() Assert.Equal(ElementType.Paragraph, builder.Build().Type); Assert.Equal(1, builder.ColumnCount); Assert.Equal(1, builder.Build().ColumnCount); - Assert.Equal("text", ((KMarkdownElementBuilder) builder.Fields[0]).Content); - Assert.Equal("text", ((KMarkdownElement) builder.Build().Fields[0]).Content); + Assert.Equal("text", ((KMarkdownElementBuilder)builder.Fields[0]).Content); + Assert.Equal("text", ((KMarkdownElement)builder.Build().Fields[0]).Content); builder = new ParagraphStructBuilder { ColumnCount = 3, @@ -361,8 +363,8 @@ public void ParagraphStructBuilder_Constructor() Assert.Equal(ElementType.Paragraph, builder.Build().Type); Assert.Equal(3, builder.ColumnCount); Assert.Equal(3, builder.Build().ColumnCount); - Assert.Equal("PlainText", ((PlainTextElementBuilder) builder.Fields[1]).Content); - Assert.Equal("PlainText", ((PlainTextElement) builder.Build().Fields[1]).Content); + Assert.Equal("PlainText", ((PlainTextElementBuilder)builder.Fields[1]).Content); + Assert.Equal("PlainText", ((PlainTextElement)builder.Build().Fields[1]).Content); } [Fact] @@ -370,12 +372,12 @@ public void ParagraphStructBuilder_AddFieldAction() { var builder = new ParagraphStructBuilder(); builder.AddField(b => b.WithContent("text")); - Assert.Equal("text", ((KMarkdownElementBuilder) builder.Fields[0]).Content); - Assert.Equal("text", ((KMarkdownElement) builder.Build().Fields[0]).Content); + Assert.Equal("text", ((KMarkdownElementBuilder)builder.Fields[0]).Content); + Assert.Equal("text", ((KMarkdownElement)builder.Build().Fields[0]).Content); builder = new ParagraphStructBuilder(); builder.AddField(b => b.WithContent("text")); - Assert.Equal("text", ((PlainTextElementBuilder) builder.Fields[0]).Content); - Assert.Equal("text", ((PlainTextElement) builder.Build().Fields[0]).Content); + Assert.Equal("text", ((PlainTextElementBuilder)builder.Fields[0]).Content); + Assert.Equal("text", ((PlainTextElement)builder.Build().Fields[0]).Content); } [Fact] @@ -409,4 +411,4 @@ public void ParagraphStructBuilder_InvalidColumnCount(int columnCount) { Assert.Throws(() => new ParagraphStructBuilder().WithColumnCount(columnCount)); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/EmojiTests.cs b/test/Kook.Net.Tests.Unit/EmojiTests.cs index 99680971..68875411 100644 --- a/test/Kook.Net.Tests.Unit/EmojiTests.cs +++ b/test/Kook.Net.Tests.Unit/EmojiTests.cs @@ -28,7 +28,7 @@ public void Test_Invalid_Emoji_Parse(string input) Assert.False(Emoji.TryParse(input, out _)); Assert.Throws(() => Emoji.Parse(input)); } - + [Theory] [InlineData("[:test:1990044438283387/aIVQrtPv4z10b10b]", "test", "1990044438283387/aIVQrtPv4z10b10b", TagMode.PlainText)] [InlineData("(emj)test(emj)[1990044438283387/aIVQrtPv4z10b10b]", "test", "1990044438283387/aIVQrtPv4z10b10b", TagMode.KMarkdown)] @@ -50,4 +50,4 @@ public void Test_Invalid_Emote_Parse(string input, TagMode tagMode) Assert.False(Emote.TryParse(input, out _, tagMode)); Assert.Throws(() => Emote.Parse(input, tagMode)); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/FormatTests.cs b/test/Kook.Net.Tests.Unit/FormatTests.cs index bc220121..23f66c19 100644 --- a/test/Kook.Net.Tests.Unit/FormatTests.cs +++ b/test/Kook.Net.Tests.Unit/FormatTests.cs @@ -75,4 +75,4 @@ public void StripMarkdown(string input, string expected) var test = Format.StripMarkDown(input); Assert.Equal(expected, test); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/GuildHelperTests.cs b/test/Kook.Net.Tests.Unit/GuildHelperTests.cs index 6958c683..a00dfdbe 100644 --- a/test/Kook.Net.Tests.Unit/GuildHelperTests.cs +++ b/test/Kook.Net.Tests.Unit/GuildHelperTests.cs @@ -1,5 +1,5 @@ -using Kook.Rest; using FluentAssertions; +using Kook.Rest; using Moq; using System; using Xunit; @@ -26,7 +26,7 @@ public void GetMaxBitrate(BoostLevel level, int factor) actual.Should().Be(expected); } - + [Theory] [InlineData(BoostLevel.None, 5)] [InlineData(BoostLevel.Level1, 20)] diff --git a/test/Kook.Net.Tests.Unit/GuildPermissionsTests.cs b/test/Kook.Net.Tests.Unit/GuildPermissionsTests.cs index 9dcf3852..c8de4d46 100644 --- a/test/Kook.Net.Tests.Unit/GuildPermissionsTests.cs +++ b/test/Kook.Net.Tests.Unit/GuildPermissionsTests.cs @@ -18,7 +18,7 @@ public class GuildPermissionsTests public void DefaultConstructor() { var p = new GuildPermissions(); - Assert.Equal((ulong) 0, p.RawValue); + Assert.Equal((ulong)0, p.RawValue); Assert.Equal(GuildPermissions.None.RawValue, p.RawValue); } @@ -58,7 +58,7 @@ void AssertFlag(Func cstr, GuildPermission flag) // ensure flag set to true Assert.True(p.Has(flag)); // ensure only this flag is set - Assert.Equal((ulong) flag, p.RawValue); + Assert.Equal((ulong)flag, p.RawValue); } AssertFlag(() => new GuildPermissions(administrator: true), GuildPermission.Administrator); @@ -159,6 +159,6 @@ void AssertUtil(GuildPermission permission, AssertUtil(GuildPermission.MuteMembers, x => x.MuteMembers, (p, enable) => p.Modify(muteMembers: enable)); AssertUtil(GuildPermission.ManageNicknames, x => x.ManageNicknames, (p, enable) => p.Modify(manageNicknames: enable)); AssertUtil(GuildPermission.PlaySoundtrack, x => x.PlaySoundtrack, (p, enable) => p.Modify(playSoundtrack: enable)); - + } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/MentionUtilsTests.cs b/test/Kook.Net.Tests.Unit/MentionUtilsTests.cs index fa02633a..bba3bc3d 100644 --- a/test/Kook.Net.Tests.Unit/MentionUtilsTests.cs +++ b/test/Kook.Net.Tests.Unit/MentionUtilsTests.cs @@ -146,4 +146,4 @@ public void ParseRole_Null() Assert.Throws(() => MentionUtils.TryParseRole(null, out _, TagMode.PlainText)); Assert.Throws(() => MentionUtils.TryParseRole(null, out _, TagMode.KMarkdown)); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/MessageHelperTests.cs b/test/Kook.Net.Tests.Unit/MessageHelperTests.cs index 741abc54..abf66dc5 100644 --- a/test/Kook.Net.Tests.Unit/MessageHelperTests.cs +++ b/test/Kook.Net.Tests.Unit/MessageHelperTests.cs @@ -1,5 +1,5 @@ -using Xunit; using Kook.Rest; +using Xunit; namespace Kook; @@ -111,4 +111,4 @@ public void ParseHere(string here) var result = MessageHelper.ParseTags(here, null, null, null, TagMode.KMarkdown); Assert.Contains(result, x => x.Type == TagType.HereMention); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/MockedEntities/MockedCategoryChannel.cs b/test/Kook.Net.Tests.Unit/MockedEntities/MockedCategoryChannel.cs index eab41d42..42990802 100644 --- a/test/Kook.Net.Tests.Unit/MockedEntities/MockedCategoryChannel.cs +++ b/test/Kook.Net.Tests.Unit/MockedEntities/MockedCategoryChannel.cs @@ -98,4 +98,4 @@ public Task DeleteAsync(RequestOptions options = null) { throw new NotImplementedException(); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/MockedEntities/MockedDMChannel.cs b/test/Kook.Net.Tests.Unit/MockedEntities/MockedDMChannel.cs index a7f3b9fe..27b4274e 100644 --- a/test/Kook.Net.Tests.Unit/MockedEntities/MockedDMChannel.cs +++ b/test/Kook.Net.Tests.Unit/MockedEntities/MockedDMChannel.cs @@ -140,4 +140,4 @@ public Task ModifyMessageAsync(Guid messageId, Action func, R Guid IEntity.Id => throw new NotImplementedException(); Guid IDMChannel.Id => throw new NotImplementedException(); -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/MockedEntities/MockedInvalidChannel.cs b/test/Kook.Net.Tests.Unit/MockedEntities/MockedInvalidChannel.cs index 2495424c..c4d4bdb8 100644 --- a/test/Kook.Net.Tests.Unit/MockedEntities/MockedInvalidChannel.cs +++ b/test/Kook.Net.Tests.Unit/MockedEntities/MockedInvalidChannel.cs @@ -24,4 +24,4 @@ public IAsyncEnumerable> GetUsersAsync(CacheMode mode { throw new NotImplementedException(); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/MockedEntities/MockedTextChannel.cs b/test/Kook.Net.Tests.Unit/MockedEntities/MockedTextChannel.cs index b80a533b..43da2397 100644 --- a/test/Kook.Net.Tests.Unit/MockedEntities/MockedTextChannel.cs +++ b/test/Kook.Net.Tests.Unit/MockedEntities/MockedTextChannel.cs @@ -222,4 +222,4 @@ public Task> GetPinnedMessagesAsync(RequestOptions { throw new NotImplementedException(); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/MockedEntities/MockedVoiceChannel.cs b/test/Kook.Net.Tests.Unit/MockedEntities/MockedVoiceChannel.cs index 42594326..40c28e84 100644 --- a/test/Kook.Net.Tests.Unit/MockedEntities/MockedVoiceChannel.cs +++ b/test/Kook.Net.Tests.Unit/MockedEntities/MockedVoiceChannel.cs @@ -150,4 +150,4 @@ public Task> GetConnectedUsersAsync(CacheMode mode = { throw new NotImplementedException(); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/ModuleBuilderTests.cs b/test/Kook.Net.Tests.Unit/ModuleBuilderTests.cs index b43a148a..20c0fa03 100644 --- a/test/Kook.Net.Tests.Unit/ModuleBuilderTests.cs +++ b/test/Kook.Net.Tests.Unit/ModuleBuilderTests.cs @@ -94,10 +94,10 @@ public void SectionModuleBuilder_Constructor() .WithAccessory(new ImageElementBuilder().WithSource(Icon)); Assert.Equal(ModuleType.Section, builder.Type); Assert.Equal(ModuleType.Section, builder.Build().Type); - Assert.Equal("text", ((PlainTextElementBuilder) builder.Text).Content); - Assert.Equal("text", ((PlainTextElement) builder.Build().Text).Content); - Assert.Equal(Icon, ((ImageElementBuilder) builder.Accessory).Source); - Assert.Equal(Icon, ((ImageElement) builder.Build().Accessory).Source); + Assert.Equal("text", ((PlainTextElementBuilder)builder.Text).Content); + Assert.Equal("text", ((PlainTextElement)builder.Build().Text).Content); + Assert.Equal(Icon, ((ImageElementBuilder)builder.Accessory).Source); + Assert.Equal(Icon, ((ImageElement)builder.Build().Accessory).Source); builder = new SectionModuleBuilder { Mode = SectionAccessoryMode.Right, @@ -106,10 +106,10 @@ public void SectionModuleBuilder_Constructor() }; Assert.Equal(ModuleType.Section, builder.Type); Assert.Equal(ModuleType.Section, builder.Build().Type); - Assert.Equal("content", ((KMarkdownElementBuilder) builder.Text).Content); - Assert.Equal("content", ((KMarkdownElement) builder.Build().Text).Content); - Assert.Equal("button", ((KMarkdownElementBuilder) ((ButtonElementBuilder) builder.Accessory).Text).Content); - Assert.Equal("button", ((KMarkdownElement) ((ButtonElement) builder.Build().Accessory).Text).Content); + Assert.Equal("content", ((KMarkdownElementBuilder)builder.Text).Content); + Assert.Equal("content", ((KMarkdownElement)builder.Build().Text).Content); + Assert.Equal("button", ((KMarkdownElementBuilder)((ButtonElementBuilder)builder.Accessory).Text).Content); + Assert.Equal("button", ((KMarkdownElement)((ButtonElement)builder.Build().Accessory).Text).Content); } [Fact] @@ -119,8 +119,8 @@ public void SectionModuleBuilder_WithTextAction() .WithText(b => b.WithContent("text")); Assert.IsType(builder.Text); Assert.IsType(builder.Build().Text); - Assert.Equal("text", ((PlainTextElementBuilder) builder.Text).Content); - Assert.Equal("text", ((PlainTextElement) builder.Build().Text).Content); + Assert.Equal("text", ((PlainTextElementBuilder)builder.Text).Content); + Assert.Equal("text", ((PlainTextElement)builder.Build().Text).Content); } [Fact] @@ -130,10 +130,10 @@ public void SectionModuleBuilder_WithAccessoryAction() .WithAccessory(b => b.WithSource(Icon)); Assert.IsType(builder.Accessory); Assert.IsType(builder.Build().Accessory); - Assert.Equal(Icon, ((ImageElementBuilder) builder.Accessory).Source); - Assert.Equal(Icon, ((ImageElement) builder.Build().Accessory).Source); + Assert.Equal(Icon, ((ImageElementBuilder)builder.Accessory).Source); + Assert.Equal(Icon, ((ImageElement)builder.Build().Accessory).Source); } - + [Fact] public void SectionModuleBuilder_InvalidText() { @@ -174,7 +174,7 @@ public void SectionModuleBuilder_InvalidButtonPosition() .WithAccessory(b => b.WithText("button")); Assert.Throws(() => builder.Build()); } - + [Fact] public void ImageGroupBuilder_Constructor() { @@ -234,7 +234,7 @@ public void ImageGroupBuilder_InvalidElements() Elements = Enumerable.Repeat(new ImageElementBuilder().WithSource(Icon), 10).ToList() }); } - + [Fact] public void ContainerBuilder_Constructor() { @@ -294,7 +294,7 @@ public void ContainerBuilder_InvalidElements() Elements = Enumerable.Repeat(new ImageElementBuilder().WithSource(Icon), 10).ToList() }); } - + [Fact] public void ActionGroupBuilder_Constructor() { @@ -416,7 +416,7 @@ public void ContextBuilder_InvalidElements() Elements = Enumerable.Repeat(new ButtonElementBuilder().WithText(Name) as IElementBuilder, 11).ToList() }); } - + [Fact] public void DividerModuleBuilder_Constructor() { @@ -543,7 +543,7 @@ public void AudioModuleBuilder_InvalidSource(string source) var builder = new AudioModuleBuilder().WithSource(Url).WithCover(Icon); Assert.Equal(Url, builder.Source); Assert.Equal(Url, builder.Build().Source); - + builder = new AudioModuleBuilder().WithSource(source).WithCover(Icon); Assert.Equal(source, builder.Source); Assert.ThrowsAny(() => builder.Build()); @@ -558,7 +558,7 @@ public void AudioModuleBuilder_InvalidCover(string source) var builder = new AudioModuleBuilder().WithSource(Url).WithCover(Icon); Assert.Equal(Icon, builder.Cover); Assert.Equal(Icon, builder.Build().Cover); - + builder = new AudioModuleBuilder().WithSource(Url).WithCover(source); Assert.Equal(source, builder.Cover); Assert.ThrowsAny(() => builder.Build()); @@ -643,7 +643,7 @@ public void CountdownModuleBuilder_InvalidTimes() Assert.ThrowsAny(() => builder.Build()); } } - + [Fact] public void InviteModuleBuilder_Constructor() { @@ -677,4 +677,4 @@ public void InviteModuleBuilder_ImplicitConversion(string text) Assert.Equal(text, builder.Code); Assert.Equal(text, builder.Build().Code); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/TimeSpanTypeReaderTests.cs b/test/Kook.Net.Tests.Unit/TimeSpanTypeReaderTests.cs index b2c4a3e4..2acfebba 100644 --- a/test/Kook.Net.Tests.Unit/TimeSpanTypeReaderTests.cs +++ b/test/Kook.Net.Tests.Unit/TimeSpanTypeReaderTests.cs @@ -67,4 +67,4 @@ public void TestTimeSpanParse(string input, bool isNegative) Assert.True(actual.Days == 0 || actual.Days == 4); } } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/TokenUtilsTests.cs b/test/Kook.Net.Tests.Unit/TokenUtilsTests.cs index 48c8e50c..32cf69f4 100644 --- a/test/Kook.Net.Tests.Unit/TokenUtilsTests.cs +++ b/test/Kook.Net.Tests.Unit/TokenUtilsTests.cs @@ -28,7 +28,7 @@ public void NullOrWhitespaceToken(string token) foreach (TokenType tokenType in (TokenType[])Enum.GetValues(typeof(TokenType))) Assert.Throws(() => TokenUtils.ValidateToken(tokenType, token)); } - + /// /// Tests the behavior of /// to see that valid Bot tokens do not throw Exceptions. @@ -47,7 +47,7 @@ public void BotTokenDoesNotThrowExceptions(string token) { TokenUtils.ValidateToken(TokenType.Bot, token); } - + /// /// Tests the usage of with /// a Bot token that is invalid. @@ -78,7 +78,7 @@ public void BotTokenInvalidThrowsArgumentException(string token) { Assert.Throws(() => TokenUtils.ValidateToken(TokenType.Bot, token)); } - + /// /// Tests the behavior of /// to see that an is thrown when an invalid @@ -115,7 +115,7 @@ public void CheckBotTokenValidity(string token, bool expected) { Assert.Equal(expected, TokenUtils.CheckBotTokenValidity(token)); } - + [Theory] // cannot pass a ulong? as a param in InlineData, so have to have a separate param // indicating if a value is null @@ -134,4 +134,4 @@ public void DecodeBase64UserId(string encodedUserId, bool isNull, ulong expected else Assert.Equal(expectedUserId, result); } -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/TypeReaderTests.cs b/test/Kook.Net.Tests.Unit/TypeReaderTests.cs index 3d211481..7c4ad671 100644 --- a/test/Kook.Net.Tests.Unit/TypeReaderTests.cs +++ b/test/Kook.Net.Tests.Unit/TypeReaderTests.cs @@ -130,4 +130,4 @@ public sealed class TestModule : ModuleBase { [Command("test")] public Task TestCommand(ArgumentType arg) => Task.Delay(0); -} \ No newline at end of file +} diff --git a/test/Kook.Net.Tests.Unit/UrlValidationTests.cs b/test/Kook.Net.Tests.Unit/UrlValidationTests.cs index 16ae9292..a32de19b 100644 --- a/test/Kook.Net.Tests.Unit/UrlValidationTests.cs +++ b/test/Kook.Net.Tests.Unit/UrlValidationTests.cs @@ -1,5 +1,5 @@ -using System; using Kook.Utils; +using System; using Xunit; namespace Kook; @@ -14,7 +14,7 @@ public void UrlValidation_ValidUrl(string url) { Assert.True(UrlValidation.Validate(url)); } - + [Theory] [InlineData(null)] [InlineData("")] @@ -22,7 +22,7 @@ public void UrlValidation_EmptyUrl(string url) { Assert.False(UrlValidation.Validate(url)); } - + [Theory] [InlineData(" ")] [InlineData("kaiheila.net")] @@ -31,7 +31,7 @@ public void UrlValidation_InvalidUrl(string url) { Assert.Throws(() => UrlValidation.Validate(url)); } - + [Theory] [InlineData("http://img.kaiheila.cn/assets/2021-01/7kr4FkWpLV0ku0ku.jpeg")] [InlineData("https://img.kookapp.cn/assets/2021-01/7kr4FkWpLV0ku0ku.jpeg")] @@ -41,7 +41,7 @@ public void UrlValidation_ValidAssetUrl(string url) { Assert.True(UrlValidation.ValidateKookAssetUrl(url)); } - + [Theory] [InlineData(null)] [InlineData("")] @@ -49,7 +49,7 @@ public void UrlValidation_EmptyAssetUrl(string url) { Assert.False(UrlValidation.ValidateKookAssetUrl(url)); } - + [Theory] [InlineData(" ")] [InlineData("kaiheila.net")] @@ -62,4 +62,4 @@ public void UrlValidation_InvalidAssetUrl(string url) { Assert.Throws(() => UrlValidation.ValidateKookAssetUrl(url)); } -} \ No newline at end of file +}