From 084db253f32269e364c7106898f2c1b34a8727ff Mon Sep 17 00:00:00 2001 From: Paulo Date: Fri, 6 Nov 2020 11:30:42 -0300 Subject: [PATCH 01/14] fix: limit request members batch size Discord is actually enforcing v8 limits on v6 according to https://github.com/discord/discord-api-docs/issues/2184 --- src/Discord.Net.WebSocket/DiscordSocketClient.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Discord.Net.WebSocket/DiscordSocketClient.cs b/src/Discord.Net.WebSocket/DiscordSocketClient.cs index 0263f96d1..24ed8d5ff 100644 --- a/src/Discord.Net.WebSocket/DiscordSocketClient.cs +++ b/src/Discord.Net.WebSocket/DiscordSocketClient.cs @@ -370,7 +370,7 @@ namespace Discord.WebSocket { var cachedGuilds = guilds.ToImmutableArray(); - int batchSize = _gatewayIntents.HasValue ? 1 : 100; + const short batchSize = 1; ulong[] batchIds = new ulong[Math.Min(batchSize, cachedGuilds.Length)]; Task[] batchTasks = new Task[batchIds.Length]; int batchCount = (cachedGuilds.Length + (batchSize - 1)) / batchSize; From e40ca4a422a55f96235c4f567daebbdb6ac483bc Mon Sep 17 00:00:00 2001 From: Samuel <33796679+orchidalloy@users.noreply.github.com> Date: Sat, 7 Nov 2020 15:26:33 -0300 Subject: [PATCH 02/14] fix: Missing AddReactions permission for DM channels. (#1244) Co-authored-by: Samuel <33796679+Samrux@users.noreply.github.com> --- src/Discord.Net.Core/Entities/Permissions/ChannelPermissions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Discord.Net.Core/Entities/Permissions/ChannelPermissions.cs b/src/Discord.Net.Core/Entities/Permissions/ChannelPermissions.cs index 99885b070..ed675b5f3 100644 --- a/src/Discord.Net.Core/Entities/Permissions/ChannelPermissions.cs +++ b/src/Discord.Net.Core/Entities/Permissions/ChannelPermissions.cs @@ -17,7 +17,7 @@ namespace Discord /// Gets a that grants all permissions for category channels. public static readonly ChannelPermissions Category = new ChannelPermissions(0b01100_1111110_1111111110001_010001); /// Gets a that grants all permissions for direct message channels. - public static readonly ChannelPermissions DM = new ChannelPermissions(0b00000_1000110_1011100110000_000000); + public static readonly ChannelPermissions DM = new ChannelPermissions(0b00000_1000110_1011100110001_000000); /// Gets a that grants all permissions for group channels. public static readonly ChannelPermissions Group = new ChannelPermissions(0b00000_1000110_0001101100000_000000); /// Gets a that grants all permissions for a given channel type. From 971d519e35a1d635d1d0634b3bfdbc9b75ceec0b Mon Sep 17 00:00:00 2001 From: Matt Smith Date: Sat, 7 Nov 2020 12:44:33 -0600 Subject: [PATCH 03/14] fix: GuildEmbed.ChannelId as nullable per API documentation (#1532) --- src/Discord.Net.Rest/API/Common/GuildEmbed.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Discord.Net.Rest/API/Common/GuildEmbed.cs b/src/Discord.Net.Rest/API/Common/GuildEmbed.cs index ff8b8e180..d81632181 100644 --- a/src/Discord.Net.Rest/API/Common/GuildEmbed.cs +++ b/src/Discord.Net.Rest/API/Common/GuildEmbed.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#pragma warning disable CS1591 using Newtonsoft.Json; namespace Discord.API @@ -8,6 +8,6 @@ namespace Discord.API [JsonProperty("enabled")] public bool Enabled { get; set; } [JsonProperty("channel_id")] - public ulong ChannelId { get; set; } + public ulong? ChannelId { get; set; } } } From a80e5ff940111f2094dd997b92d134b1584a8fd8 Mon Sep 17 00:00:00 2001 From: Radka Gustavsson Date: Sat, 7 Nov 2020 19:55:14 +0100 Subject: [PATCH 04/14] (ifcbrk) feature: Add includeRoleIds to PruneUsersAsync (#1581) * Implemented include_roles for guilds/id/prune get&post * Unnecessary using Co-authored-by: Paulo --- src/Discord.Net.Core/Entities/Guilds/IGuild.cs | 3 ++- src/Discord.Net.Rest/API/Rest/GuildPruneParams.cs | 6 +++++- src/Discord.Net.Rest/DiscordRestApiClient.cs | 3 ++- src/Discord.Net.Rest/Entities/Guilds/GuildHelper.cs | 10 +++++----- src/Discord.Net.Rest/Entities/Guilds/RestGuild.cs | 6 +++--- .../Entities/Guilds/SocketGuild.cs | 4 ++-- 6 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/Discord.Net.Core/Entities/Guilds/IGuild.cs b/src/Discord.Net.Core/Entities/Guilds/IGuild.cs index 81b5e8dd9..8392bcd58 100644 --- a/src/Discord.Net.Core/Entities/Guilds/IGuild.cs +++ b/src/Discord.Net.Core/Entities/Guilds/IGuild.cs @@ -705,11 +705,12 @@ namespace Discord /// The number of days required for the users to be kicked. /// Whether this prune action is a simulation. /// The options to be used when sending the request. + /// An array of role IDs to be included in the prune of users who do not have any additional roles. /// /// A task that represents the asynchronous prune operation. The task result contains the number of users to /// be or has been removed from this guild. /// - Task PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null); + Task PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null, IEnumerable includeRoleIds = null); /// /// Gets a collection of users in this guild that the name or nickname starts with the /// provided at . diff --git a/src/Discord.Net.Rest/API/Rest/GuildPruneParams.cs b/src/Discord.Net.Rest/API/Rest/GuildPruneParams.cs index 6a98d3758..e4c9192ad 100644 --- a/src/Discord.Net.Rest/API/Rest/GuildPruneParams.cs +++ b/src/Discord.Net.Rest/API/Rest/GuildPruneParams.cs @@ -9,9 +9,13 @@ namespace Discord.API.Rest [JsonProperty("days")] public int Days { get; } - public GuildPruneParams(int days) + [JsonProperty("include_roles")] + public ulong[] IncludeRoleIds { get; } + + public GuildPruneParams(int days, ulong[] includeRoleIds) { Days = days; + IncludeRoleIds = includeRoleIds; } } } diff --git a/src/Discord.Net.Rest/DiscordRestApiClient.cs b/src/Discord.Net.Rest/DiscordRestApiClient.cs index 83aa6c751..27658e7ac 100644 --- a/src/Discord.Net.Rest/DiscordRestApiClient.cs +++ b/src/Discord.Net.Rest/DiscordRestApiClient.cs @@ -853,10 +853,11 @@ namespace Discord.API Preconditions.NotEqual(guildId, 0, nameof(guildId)); Preconditions.NotNull(args, nameof(args)); Preconditions.AtLeast(args.Days, 1, nameof(args.Days)); + string endpointRoleIds = args.IncludeRoleIds?.Length > 0 ? $"&include_roles={string.Join(",", args.IncludeRoleIds)}" : ""; options = RequestOptions.CreateOrClone(options); var ids = new BucketIds(guildId: guildId); - return await SendAsync("GET", () => $"guilds/{guildId}/prune?days={args.Days}", ids, options: options).ConfigureAwait(false); + return await SendAsync("GET", () => $"guilds/{guildId}/prune?days={args.Days}{endpointRoleIds}", ids, options: options).ConfigureAwait(false); } //Guild Bans diff --git a/src/Discord.Net.Rest/Entities/Guilds/GuildHelper.cs b/src/Discord.Net.Rest/Entities/Guilds/GuildHelper.cs index ecb45fd07..225c53edf 100644 --- a/src/Discord.Net.Rest/Entities/Guilds/GuildHelper.cs +++ b/src/Discord.Net.Rest/Entities/Guilds/GuildHelper.cs @@ -404,9 +404,9 @@ namespace Discord.Rest ); } public static async Task PruneUsersAsync(IGuild guild, BaseDiscordClient client, - int days, bool simulate, RequestOptions options) + int days, bool simulate, RequestOptions options, IEnumerable includeRoleIds) { - var args = new GuildPruneParams(days); + var args = new GuildPruneParams(days, includeRoleIds?.ToArray()); GetGuildPruneCountResponse model; if (simulate) model = await client.ApiClient.GetGuildPruneCountAsync(guild.Id, args, options).ConfigureAwait(false); @@ -479,7 +479,7 @@ namespace Discord.Rest var emote = await client.ApiClient.GetGuildEmoteAsync(guild.Id, id, options).ConfigureAwait(false); return emote.ToEntity(); } - public static async Task CreateEmoteAsync(IGuild guild, BaseDiscordClient client, string name, Image image, Optional> roles, + public static async Task CreateEmoteAsync(IGuild guild, BaseDiscordClient client, string name, Image image, Optional> roles, RequestOptions options) { var apiargs = new CreateGuildEmoteParams @@ -494,7 +494,7 @@ namespace Discord.Rest return emote.ToEntity(); } /// is null. - public static async Task ModifyEmoteAsync(IGuild guild, BaseDiscordClient client, ulong id, Action func, + public static async Task ModifyEmoteAsync(IGuild guild, BaseDiscordClient client, ulong id, Action func, RequestOptions options) { if (func == null) throw new ArgumentNullException(paramName: nameof(func)); @@ -512,7 +512,7 @@ namespace Discord.Rest var emote = await client.ApiClient.ModifyGuildEmoteAsync(guild.Id, id, apiargs, options).ConfigureAwait(false); return emote.ToEntity(); } - public static Task DeleteEmoteAsync(IGuild guild, BaseDiscordClient client, ulong id, RequestOptions options) + public static Task DeleteEmoteAsync(IGuild guild, BaseDiscordClient client, ulong id, RequestOptions options) => client.ApiClient.DeleteGuildEmoteAsync(guild.Id, id, options); } } diff --git a/src/Discord.Net.Rest/Entities/Guilds/RestGuild.cs b/src/Discord.Net.Rest/Entities/Guilds/RestGuild.cs index f0b5be0f7..482eaf556 100644 --- a/src/Discord.Net.Rest/Entities/Guilds/RestGuild.cs +++ b/src/Discord.Net.Rest/Entities/Guilds/RestGuild.cs @@ -205,7 +205,7 @@ namespace Discord.Rest role?.Update(model); } } - + /// public Task LeaveAsync(RequestOptions options = null) => GuildHelper.LeaveAsync(this, Discord, options); @@ -631,8 +631,8 @@ namespace Discord.Rest /// A task that represents the asynchronous prune operation. The task result contains the number of users to /// be or has been removed from this guild. /// - public Task PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null) - => GuildHelper.PruneUsersAsync(this, Discord, days, simulate, options); + public Task PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null, IEnumerable includeRoleIds = null) + => GuildHelper.PruneUsersAsync(this, Discord, days, simulate, options, includeRoleIds); /// /// Gets a collection of users in this guild that the name or nickname starts with the diff --git a/src/Discord.Net.WebSocket/Entities/Guilds/SocketGuild.cs b/src/Discord.Net.WebSocket/Entities/Guilds/SocketGuild.cs index 160b91526..a08ba06ef 100644 --- a/src/Discord.Net.WebSocket/Entities/Guilds/SocketGuild.cs +++ b/src/Discord.Net.WebSocket/Entities/Guilds/SocketGuild.cs @@ -746,8 +746,8 @@ namespace Discord.WebSocket return null; } /// - public Task PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null) - => GuildHelper.PruneUsersAsync(this, Discord, days, simulate, options); + public Task PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null, IEnumerable includeRoleIds = null) + => GuildHelper.PruneUsersAsync(this, Discord, days, simulate, options, includeRoleIds); internal SocketGuildUser AddOrUpdateUser(UserModel model) { From 2592264acbbd49f7f1e481a82277d10a5bdea414 Mon Sep 17 00:00:00 2001 From: "bakabaka.bunbun" <54648150+bakabun@users.noreply.github.com> Date: Sun, 8 Nov 2020 02:10:13 +0700 Subject: [PATCH 05/14] feature: Add "View Guild Insights" to GuildPermission (#1619) * feature: Add "View Guild Insights" permission * Add missing summary Co-authored-by: Paulo --- .../Entities/Permissions/GuildPermission.cs | 4 ++++ .../Entities/Permissions/GuildPermissions.cs | 11 +++++++++-- test/Discord.Net.Tests.Unit/GuildPermissionsTests.cs | 2 ++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/Discord.Net.Core/Entities/Permissions/GuildPermission.cs b/src/Discord.Net.Core/Entities/Permissions/GuildPermission.cs index 3c8a5e810..645b67489 100644 --- a/src/Discord.Net.Core/Entities/Permissions/GuildPermission.cs +++ b/src/Discord.Net.Core/Entities/Permissions/GuildPermission.cs @@ -51,6 +51,10 @@ namespace Discord /// authentication when used on a guild that has server-wide 2FA enabled. /// ManageGuild = 0x00_00_00_20, + /// + /// Allows for viewing of guild insights + /// + ViewGuildInsights = 0x00_08_00_00, // Text /// diff --git a/src/Discord.Net.Core/Entities/Permissions/GuildPermissions.cs b/src/Discord.Net.Core/Entities/Permissions/GuildPermissions.cs index a5adad47c..ba6757fc6 100644 --- a/src/Discord.Net.Core/Entities/Permissions/GuildPermissions.cs +++ b/src/Discord.Net.Core/Entities/Permissions/GuildPermissions.cs @@ -12,7 +12,7 @@ namespace Discord /// Gets a that grants all guild permissions for webhook users. public static readonly GuildPermissions Webhook = new GuildPermissions(0b00000_0000000_0001101100000_000000); /// Gets a that grants all guild permissions. - public static readonly GuildPermissions All = new GuildPermissions(0b11111_1111110_1111111111111_111111); + public static readonly GuildPermissions All = new GuildPermissions(0b11111_1111111_1111111111111_111111); /// Gets a packed value representing all the permissions in this . public ulong RawValue { get; } @@ -34,6 +34,8 @@ namespace Discord public bool AddReactions => Permissions.GetValue(RawValue, GuildPermission.AddReactions); /// If true, a user may view the audit log. public bool ViewAuditLog => Permissions.GetValue(RawValue, GuildPermission.ViewAuditLog); + /// If true, a user may view the guild insights. + public bool ViewGuildInsights => Permissions.GetValue(RawValue, GuildPermission.ViewGuildInsights); /// If True, a user may join channels. [Obsolete("Use ViewChannel instead.")] @@ -97,6 +99,7 @@ namespace Discord bool? manageGuild = null, bool? addReactions = null, bool? viewAuditLog = null, + bool? viewGuildInsights = null, bool? viewChannel = null, bool? sendMessages = null, bool? sendTTSMessages = null, @@ -130,6 +133,7 @@ namespace Discord Permissions.SetValue(ref value, manageGuild, GuildPermission.ManageGuild); Permissions.SetValue(ref value, addReactions, GuildPermission.AddReactions); Permissions.SetValue(ref value, viewAuditLog, GuildPermission.ViewAuditLog); + Permissions.SetValue(ref value, viewGuildInsights, GuildPermission.ViewGuildInsights); Permissions.SetValue(ref value, viewChannel, GuildPermission.ViewChannel); Permissions.SetValue(ref value, sendMessages, GuildPermission.SendMessages); Permissions.SetValue(ref value, sendTTSMessages, GuildPermission.SendTTSMessages); @@ -166,6 +170,7 @@ namespace Discord bool manageGuild = false, bool addReactions = false, bool viewAuditLog = false, + bool viewGuildInsights = false, bool viewChannel = false, bool sendMessages = false, bool sendTTSMessages = false, @@ -198,6 +203,7 @@ namespace Discord manageGuild: manageGuild, addReactions: addReactions, viewAuditLog: viewAuditLog, + viewGuildInsights: viewGuildInsights, viewChannel: viewChannel, sendMessages: sendMessages, sendTTSMessages: sendTTSMessages, @@ -231,6 +237,7 @@ namespace Discord bool? manageGuild = null, bool? addReactions = null, bool? viewAuditLog = null, + bool? viewGuildInsights = null, bool? viewChannel = null, bool? sendMessages = null, bool? sendTTSMessages = null, @@ -254,7 +261,7 @@ namespace Discord bool? manageWebhooks = null, bool? manageEmojis = null) => new GuildPermissions(RawValue, createInstantInvite, kickMembers, banMembers, administrator, manageChannels, manageGuild, addReactions, - viewAuditLog, viewChannel, sendMessages, sendTTSMessages, manageMessages, embedLinks, attachFiles, + viewAuditLog, viewGuildInsights, viewChannel, sendMessages, sendTTSMessages, manageMessages, embedLinks, attachFiles, readMessageHistory, mentionEveryone, useExternalEmojis, connect, speak, muteMembers, deafenMembers, moveMembers, useVoiceActivation, prioritySpeaker, stream, changeNickname, manageNicknames, manageRoles, manageWebhooks, manageEmojis); diff --git a/test/Discord.Net.Tests.Unit/GuildPermissionsTests.cs b/test/Discord.Net.Tests.Unit/GuildPermissionsTests.cs index f0611fa24..cd29b2606 100644 --- a/test/Discord.Net.Tests.Unit/GuildPermissionsTests.cs +++ b/test/Discord.Net.Tests.Unit/GuildPermissionsTests.cs @@ -69,6 +69,7 @@ namespace Discord AssertFlag(() => new GuildPermissions(manageGuild: true), GuildPermission.ManageGuild); AssertFlag(() => new GuildPermissions(addReactions: true), GuildPermission.AddReactions); AssertFlag(() => new GuildPermissions(viewAuditLog: true), GuildPermission.ViewAuditLog); + AssertFlag(() => new GuildPermissions(viewGuildInsights: true), GuildPermission.ViewGuildInsights); AssertFlag(() => new GuildPermissions(viewChannel: true), GuildPermission.ViewChannel); AssertFlag(() => new GuildPermissions(sendMessages: true), GuildPermission.SendMessages); AssertFlag(() => new GuildPermissions(sendTTSMessages: true), GuildPermission.SendTTSMessages); @@ -141,6 +142,7 @@ namespace Discord AssertUtil(GuildPermission.ManageGuild, x => x.ManageGuild, (p, enable) => p.Modify(manageGuild: enable)); AssertUtil(GuildPermission.AddReactions, x => x.AddReactions, (p, enable) => p.Modify(addReactions: enable)); AssertUtil(GuildPermission.ViewAuditLog, x => x.ViewAuditLog, (p, enable) => p.Modify(viewAuditLog: enable)); + AssertUtil(GuildPermission.ViewGuildInsights, x => x.ViewGuildInsights, (p, enable) => p.Modify(viewGuildInsights: enable)); AssertUtil(GuildPermission.ViewChannel, x => x.ViewChannel, (p, enable) => p.Modify(viewChannel: enable)); AssertUtil(GuildPermission.SendMessages, x => x.SendMessages, (p, enable) => p.Modify(sendMessages: enable)); AssertUtil(GuildPermission.SendTTSMessages, x => x.SendTTSMessages, (p, enable) => p.Modify(sendTTSMessages: enable)); From a2af9857ca2fc042c33b6243e9e1b71a1960a656 Mon Sep 17 00:00:00 2001 From: Paulo Date: Sat, 7 Nov 2020 16:15:46 -0300 Subject: [PATCH 06/14] fix: Audio stream dispose (#1667) * Fix audio dispose * Missed a few --- .../Audio/Streams/BufferedWriteStream.cs | 3 +++ .../Audio/Streams/OpusDecodeStream.cs | 6 ++++-- .../Audio/Streams/OpusEncodeStream.cs | 8 +++++--- src/Discord.Net.WebSocket/Audio/Streams/RTPReadStream.cs | 7 +++++++ .../Audio/Streams/RTPWriteStream.cs | 9 ++++++++- .../Audio/Streams/SodiumDecryptStream.cs | 7 +++++++ .../Audio/Streams/SodiumEncryptStream.cs | 7 +++++++ 7 files changed, 41 insertions(+), 6 deletions(-) diff --git a/src/Discord.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs b/src/Discord.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs index 16ad0ae89..a2de252a2 100644 --- a/src/Discord.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs +++ b/src/Discord.Net.WebSocket/Audio/Streams/BufferedWriteStream.cs @@ -61,14 +61,17 @@ namespace Discord.Audio.Streams _task = Run(); } + protected override void Dispose(bool disposing) { if (disposing) { _disposeTokenSource?.Cancel(); _disposeTokenSource?.Dispose(); + _cancelTokenSource?.Cancel(); _cancelTokenSource?.Dispose(); _queueLock?.Dispose(); + _next.Dispose(); } base.Dispose(disposing); } diff --git a/src/Discord.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs b/src/Discord.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs index 1861e3554..ad1c285e8 100644 --- a/src/Discord.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs +++ b/src/Discord.Net.WebSocket/Audio/Streams/OpusDecodeStream.cs @@ -68,10 +68,12 @@ namespace Discord.Audio.Streams protected override void Dispose(bool disposing) { - base.Dispose(disposing); - if (disposing) + { _decoder.Dispose(); + _next.Dispose(); + } + base.Dispose(disposing); } } } diff --git a/src/Discord.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs b/src/Discord.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs index 035b92b30..05d12b490 100644 --- a/src/Discord.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs +++ b/src/Discord.Net.WebSocket/Audio/Streams/OpusEncodeStream.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading; using System.Threading.Tasks; @@ -89,10 +89,12 @@ namespace Discord.Audio.Streams protected override void Dispose(bool disposing) { - base.Dispose(disposing); - if (disposing) + { _encoder.Dispose(); + _next.Dispose(); + } + base.Dispose(disposing); } } } diff --git a/src/Discord.Net.WebSocket/Audio/Streams/RTPReadStream.cs b/src/Discord.Net.WebSocket/Audio/Streams/RTPReadStream.cs index 120f67e0d..1002502b6 100644 --- a/src/Discord.Net.WebSocket/Audio/Streams/RTPReadStream.cs +++ b/src/Discord.Net.WebSocket/Audio/Streams/RTPReadStream.cs @@ -76,5 +76,12 @@ namespace Discord.Audio.Streams (buffer[extensionOffset + 3]); return extensionOffset + 4 + (extensionLength * 4); } + + protected override void Dispose(bool disposing) + { + if (disposing) + _next.Dispose(); + base.Dispose(disposing); + } } } diff --git a/src/Discord.Net.WebSocket/Audio/Streams/RTPWriteStream.cs b/src/Discord.Net.WebSocket/Audio/Streams/RTPWriteStream.cs index ce407eada..7ecb56bee 100644 --- a/src/Discord.Net.WebSocket/Audio/Streams/RTPWriteStream.cs +++ b/src/Discord.Net.WebSocket/Audio/Streams/RTPWriteStream.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading; using System.Threading.Tasks; @@ -69,5 +69,12 @@ namespace Discord.Audio.Streams { await _next.ClearAsync(cancelToken).ConfigureAwait(false); } + + protected override void Dispose(bool disposing) + { + if (disposing) + _next.Dispose(); + base.Dispose(disposing); + } } } diff --git a/src/Discord.Net.WebSocket/Audio/Streams/SodiumDecryptStream.cs b/src/Discord.Net.WebSocket/Audio/Streams/SodiumDecryptStream.cs index 2b1a97f04..40cd6864e 100644 --- a/src/Discord.Net.WebSocket/Audio/Streams/SodiumDecryptStream.cs +++ b/src/Discord.Net.WebSocket/Audio/Streams/SodiumDecryptStream.cs @@ -44,5 +44,12 @@ namespace Discord.Audio.Streams { await _next.ClearAsync(cancelToken).ConfigureAwait(false); } + + protected override void Dispose(bool disposing) + { + if (disposing) + _next.Dispose(); + base.Dispose(disposing); + } } } diff --git a/src/Discord.Net.WebSocket/Audio/Streams/SodiumEncryptStream.cs b/src/Discord.Net.WebSocket/Audio/Streams/SodiumEncryptStream.cs index 8b3f0e302..fa1d34de5 100644 --- a/src/Discord.Net.WebSocket/Audio/Streams/SodiumEncryptStream.cs +++ b/src/Discord.Net.WebSocket/Audio/Streams/SodiumEncryptStream.cs @@ -60,5 +60,12 @@ namespace Discord.Audio.Streams { await _next.ClearAsync(cancelToken).ConfigureAwait(false); } + + protected override void Dispose(bool disposing) + { + if (disposing) + _next.Dispose(); + base.Dispose(disposing); + } } } From 1ab670b3fcab9ddb641a36359149e26ecddaa1ea Mon Sep 17 00:00:00 2001 From: Paulo Date: Sun, 8 Nov 2020 17:33:37 -0300 Subject: [PATCH 07/14] feature: Add INVITE_CREATE and INVITE_DELETE events (#1491) * Add invite events (create and delete) * Removed unused using * Fixing IInviteMetadata properties * Add two new fields to the gateway event * Better event summary and remarks * Change how to assign to target variable Co-Authored-By: Joe4evr * Applying suggested changes to TargetUserType * Renaming NotDefined to Undefined * Fixing xml docs * Changed the summary style format Co-authored-by: Joe4evr --- .../Entities/Invites/TargetUserType.cs | 14 ++ .../API/Gateway/InviteCreateEvent.cs | 31 ++++ .../API/Gateway/InviteDeleteEvent.cs | 14 ++ .../BaseSocketClient.Events.cs | 42 +++++ .../DiscordShardedClient.cs | 3 + .../DiscordSocketClient.cs | 58 +++++++ .../Entities/Invites/SocketInvite.cs | 143 ++++++++++++++++++ 7 files changed, 305 insertions(+) create mode 100644 src/Discord.Net.Core/Entities/Invites/TargetUserType.cs create mode 100644 src/Discord.Net.WebSocket/API/Gateway/InviteCreateEvent.cs create mode 100644 src/Discord.Net.WebSocket/API/Gateway/InviteDeleteEvent.cs create mode 100644 src/Discord.Net.WebSocket/Entities/Invites/SocketInvite.cs diff --git a/src/Discord.Net.Core/Entities/Invites/TargetUserType.cs b/src/Discord.Net.Core/Entities/Invites/TargetUserType.cs new file mode 100644 index 000000000..74263b888 --- /dev/null +++ b/src/Discord.Net.Core/Entities/Invites/TargetUserType.cs @@ -0,0 +1,14 @@ +namespace Discord +{ + public enum TargetUserType + { + /// + /// The invite whose target user type is not defined. + /// + Undefined = 0, + /// + /// The invite is for a Go Live stream. + /// + Stream = 1 + } +} diff --git a/src/Discord.Net.WebSocket/API/Gateway/InviteCreateEvent.cs b/src/Discord.Net.WebSocket/API/Gateway/InviteCreateEvent.cs new file mode 100644 index 000000000..e2ddd8816 --- /dev/null +++ b/src/Discord.Net.WebSocket/API/Gateway/InviteCreateEvent.cs @@ -0,0 +1,31 @@ +using Newtonsoft.Json; +using System; + +namespace Discord.API.Gateway +{ + internal class InviteCreateEvent + { + [JsonProperty("channel_id")] + public ulong ChannelId { get; set; } + [JsonProperty("code")] + public string Code { get; set; } + [JsonProperty("created_at")] + public DateTimeOffset CreatedAt { get; set; } + [JsonProperty("guild_id")] + public Optional GuildId { get; set; } + [JsonProperty("inviter")] + public Optional Inviter { get; set; } + [JsonProperty("max_age")] + public int MaxAge { get; set; } + [JsonProperty("max_uses")] + public int MaxUses { get; set; } + [JsonProperty("target_user")] + public Optional TargetUser { get; set; } + [JsonProperty("target_user_type")] + public Optional TargetUserType { get; set; } + [JsonProperty("temporary")] + public bool Temporary { get; set; } + [JsonProperty("uses")] + public int Uses { get; set; } + } +} diff --git a/src/Discord.Net.WebSocket/API/Gateway/InviteDeleteEvent.cs b/src/Discord.Net.WebSocket/API/Gateway/InviteDeleteEvent.cs new file mode 100644 index 000000000..54bc75595 --- /dev/null +++ b/src/Discord.Net.WebSocket/API/Gateway/InviteDeleteEvent.cs @@ -0,0 +1,14 @@ +using Newtonsoft.Json; + +namespace Discord.API.Gateway +{ + internal class InviteDeleteEvent + { + [JsonProperty("channel_id")] + public ulong ChannelId { get; set; } + [JsonProperty("code")] + public string Code { get; set; } + [JsonProperty("guild_id")] + public Optional GuildId { get; set; } + } +} diff --git a/src/Discord.Net.WebSocket/BaseSocketClient.Events.cs b/src/Discord.Net.WebSocket/BaseSocketClient.Events.cs index 2cd62b3e8..966aec7fa 100644 --- a/src/Discord.Net.WebSocket/BaseSocketClient.Events.cs +++ b/src/Discord.Net.WebSocket/BaseSocketClient.Events.cs @@ -389,5 +389,47 @@ namespace Discord.WebSocket remove { _recipientRemovedEvent.Remove(value); } } internal readonly AsyncEvent> _recipientRemovedEvent = new AsyncEvent>(); + + //Invites + /// + /// Fired when an invite is created. + /// + /// + /// + /// This event is fired when an invite is created. The event handler must return a + /// and accept a as its parameter. + /// + /// + /// The invite created will be passed into the parameter. + /// + /// + public event Func InviteCreated + { + add { _inviteCreatedEvent.Add(value); } + remove { _inviteCreatedEvent.Remove(value); } + } + internal readonly AsyncEvent> _inviteCreatedEvent = new AsyncEvent>(); + /// + /// Fired when an invite is deleted. + /// + /// + /// + /// This event is fired when an invite is deleted. The event handler must return + /// a and accept a and + /// as its parameter. + /// + /// + /// The channel where this invite was created will be passed into the parameter. + /// + /// + /// The code of the deleted invite will be passed into the parameter. + /// + /// + public event Func InviteDeleted + { + add { _inviteDeletedEvent.Add(value); } + remove { _inviteDeletedEvent.Remove(value); } + } + internal readonly AsyncEvent> _inviteDeletedEvent = new AsyncEvent>(); } } diff --git a/src/Discord.Net.WebSocket/DiscordShardedClient.cs b/src/Discord.Net.WebSocket/DiscordShardedClient.cs index 930ea1585..a8780a7b0 100644 --- a/src/Discord.Net.WebSocket/DiscordShardedClient.cs +++ b/src/Discord.Net.WebSocket/DiscordShardedClient.cs @@ -338,6 +338,9 @@ namespace Discord.WebSocket client.UserIsTyping += (oldUser, newUser) => _userIsTypingEvent.InvokeAsync(oldUser, newUser); client.RecipientAdded += (user) => _recipientAddedEvent.InvokeAsync(user); client.RecipientRemoved += (user) => _recipientRemovedEvent.InvokeAsync(user); + + client.InviteCreated += (invite) => _inviteCreatedEvent.InvokeAsync(invite); + client.InviteDeleted += (channel, invite) => _inviteDeletedEvent.InvokeAsync(channel, invite); } //IDiscordClient diff --git a/src/Discord.Net.WebSocket/DiscordSocketClient.cs b/src/Discord.Net.WebSocket/DiscordSocketClient.cs index 24ed8d5ff..dfdad99fc 100644 --- a/src/Discord.Net.WebSocket/DiscordSocketClient.cs +++ b/src/Discord.Net.WebSocket/DiscordSocketClient.cs @@ -1688,6 +1688,64 @@ namespace Discord.WebSocket } break; + //Invites + case "INVITE_CREATE": + { + await _gatewayLogger.DebugAsync("Received Dispatch (INVITE_CREATE)").ConfigureAwait(false); + + var data = (payload as JToken).ToObject(_serializer); + if (State.GetChannel(data.ChannelId) is SocketGuildChannel channel) + { + var guild = channel.Guild; + if (!guild.IsSynced) + { + await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false); + return; + } + + SocketGuildUser inviter = data.Inviter.IsSpecified + ? (guild.GetUser(data.Inviter.Value.Id) ?? guild.AddOrUpdateUser(data.Inviter.Value)) + : null; + + SocketUser target = data.TargetUser.IsSpecified + ? (guild.GetUser(data.TargetUser.Value.Id) ?? (SocketUser)SocketUnknownUser.Create(this, State, data.TargetUser.Value)) + : null; + + var invite = SocketInvite.Create(this, guild, channel, inviter, target, data); + + await TimedInvokeAsync(_inviteCreatedEvent, nameof(InviteCreated), invite).ConfigureAwait(false); + } + else + { + await UnknownChannelAsync(type, data.ChannelId).ConfigureAwait(false); + return; + } + } + break; + case "INVITE_DELETE": + { + await _gatewayLogger.DebugAsync("Received Dispatch (INVITE_DELETE)").ConfigureAwait(false); + + var data = (payload as JToken).ToObject(_serializer); + if (State.GetChannel(data.ChannelId) is SocketGuildChannel channel) + { + var guild = channel.Guild; + if (!guild.IsSynced) + { + await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false); + return; + } + + await TimedInvokeAsync(_inviteDeletedEvent, nameof(InviteDeleted), channel, data.Code).ConfigureAwait(false); + } + else + { + await UnknownChannelAsync(type, data.ChannelId).ConfigureAwait(false); + return; + } + } + break; + //Ignored (User only) case "CHANNEL_PINS_ACK": await _gatewayLogger.DebugAsync("Ignored Dispatch (CHANNEL_PINS_ACK)").ConfigureAwait(false); diff --git a/src/Discord.Net.WebSocket/Entities/Invites/SocketInvite.cs b/src/Discord.Net.WebSocket/Entities/Invites/SocketInvite.cs new file mode 100644 index 000000000..fa8c56599 --- /dev/null +++ b/src/Discord.Net.WebSocket/Entities/Invites/SocketInvite.cs @@ -0,0 +1,143 @@ +using Discord.Rest; +using System; +using System.Diagnostics; +using System.Threading.Tasks; +using Model = Discord.API.Gateway.InviteCreateEvent; + +namespace Discord.WebSocket +{ + [DebuggerDisplay(@"{DebuggerDisplay,nq}")] + public class SocketInvite : SocketEntity, IInviteMetadata + { + private long _createdAtTicks; + + /// + public ulong ChannelId { get; private set; } + /// + /// Gets the channel where this invite was created. + /// + public SocketGuildChannel Channel { get; private set; } + /// + public ulong? GuildId { get; private set; } + /// + /// Gets the guild where this invite was created. + /// + public SocketGuild Guild { get; private set; } + /// + ChannelType IInvite.ChannelType + { + get + { + switch (Channel) + { + case IVoiceChannel voiceChannel: return ChannelType.Voice; + case ICategoryChannel categoryChannel: return ChannelType.Category; + case IDMChannel dmChannel: return ChannelType.DM; + case IGroupChannel groupChannel: return ChannelType.Group; + case SocketNewsChannel socketNewsChannel: return ChannelType.News; + case ITextChannel textChannel: return ChannelType.Text; + default: throw new InvalidOperationException("Invalid channel type."); + } + } + } + /// + string IInvite.ChannelName => Channel.Name; + /// + string IInvite.GuildName => Guild.Name; + /// + int? IInvite.PresenceCount => throw new NotImplementedException(); + /// + int? IInvite.MemberCount => throw new NotImplementedException(); + /// + bool IInviteMetadata.IsRevoked => throw new NotImplementedException(); + /// + public bool IsTemporary { get; private set; } + /// + int? IInviteMetadata.MaxAge { get => MaxAge; } + /// + int? IInviteMetadata.MaxUses { get => MaxUses; } + /// + int? IInviteMetadata.Uses { get => Uses; } + /// + /// Gets the time (in seconds) until the invite expires. + /// + public int MaxAge { get; private set; } + /// + /// Gets the max number of uses this invite may have. + /// + public int MaxUses { get; private set; } + /// + /// Gets the number of times this invite has been used. + /// + public int Uses { get; private set; } + /// + /// Gets the user that created this invite if available. + /// + public SocketGuildUser Inviter { get; private set; } + /// + DateTimeOffset? IInviteMetadata.CreatedAt => DateTimeUtils.FromTicks(_createdAtTicks); + /// + /// Gets when this invite was created. + /// + public DateTimeOffset CreatedAt => DateTimeUtils.FromTicks(_createdAtTicks); + /// + /// Gets the user targeted by this invite if available. + /// + public SocketUser TargetUser { get; private set; } + /// + /// Gets the type of the user targeted by this invite. + /// + public TargetUserType TargetUserType { get; private set; } + + /// + public string Code => Id; + /// + public string Url => $"{DiscordConfig.InviteUrl}{Code}"; + + internal SocketInvite(DiscordSocketClient discord, SocketGuild guild, SocketGuildChannel channel, SocketGuildUser inviter, SocketUser target, string id) + : base(discord, id) + { + Guild = guild; + Channel = channel; + Inviter = inviter; + TargetUser = target; + } + internal static SocketInvite Create(DiscordSocketClient discord, SocketGuild guild, SocketGuildChannel channel, SocketGuildUser inviter, SocketUser target, Model model) + { + var entity = new SocketInvite(discord, guild, channel, inviter, target, model.Code); + entity.Update(model); + return entity; + } + internal void Update(Model model) + { + ChannelId = model.ChannelId; + GuildId = model.GuildId.IsSpecified ? model.GuildId.Value : Guild.Id; + IsTemporary = model.Temporary; + MaxAge = model.MaxAge; + MaxUses = model.MaxUses; + Uses = model.Uses; + _createdAtTicks = model.CreatedAt.UtcTicks; + TargetUserType = model.TargetUserType.IsSpecified ? model.TargetUserType.Value : TargetUserType.Undefined; + } + + /// + public Task DeleteAsync(RequestOptions options = null) + => InviteHelper.DeleteAsync(this, Discord, options); + + /// + /// Gets the URL of the invite. + /// + /// + /// A string that resolves to the Url of the invite. + /// + public override string ToString() => Url; + private string DebuggerDisplay => $"{Url} ({Guild?.Name} / {Channel.Name})"; + + /// + IGuild IInvite.Guild => Guild; + /// + IChannel IInvite.Channel => Channel; + /// + IUser IInviteMetadata.Inviter => Inviter; + } +} From 10fcde0a32ee3a04b0a50a94d2fe4dcd876d181d Mon Sep 17 00:00:00 2001 From: Paulo Date: Sun, 8 Nov 2020 18:13:41 -0300 Subject: [PATCH 08/14] feature: Add missing application properties (including Teams) (#1604) * Add missing application properties Add IsBotPublic, BotRequiresCodeGrant, and Team properties to IApplication * To immutable list * Change list to array --- src/Discord.Net.Core/CDN.cs | 11 ++++++ src/Discord.Net.Core/Entities/IApplication.cs | 12 ++++++ src/Discord.Net.Core/Entities/Teams/ITeam.cs | 27 ++++++++++++++ .../Entities/Teams/ITeamMember.cs | 25 +++++++++++++ .../Entities/Teams/MembershipState.cs | 11 ++++++ .../API/Common/Application.cs | 8 +++- .../API/Common/MembershipState.cs | 9 +++++ src/Discord.Net.Rest/API/Common/Team.cs | 17 +++++++++ src/Discord.Net.Rest/API/Common/TeamMember.cs | 17 +++++++++ .../Entities/RestApplication.cs | 10 +++++ .../Entities/Teams/RestTeam.cs | 37 +++++++++++++++++++ .../Entities/Teams/RestTeamMember.cs | 30 +++++++++++++++ 12 files changed, 213 insertions(+), 1 deletion(-) create mode 100644 src/Discord.Net.Core/Entities/Teams/ITeam.cs create mode 100644 src/Discord.Net.Core/Entities/Teams/ITeamMember.cs create mode 100644 src/Discord.Net.Core/Entities/Teams/MembershipState.cs create mode 100644 src/Discord.Net.Rest/API/Common/MembershipState.cs create mode 100644 src/Discord.Net.Rest/API/Common/Team.cs create mode 100644 src/Discord.Net.Rest/API/Common/TeamMember.cs create mode 100644 src/Discord.Net.Rest/Entities/Teams/RestTeam.cs create mode 100644 src/Discord.Net.Rest/Entities/Teams/RestTeamMember.cs diff --git a/src/Discord.Net.Core/CDN.cs b/src/Discord.Net.Core/CDN.cs index 32ffbba90..799b037ed 100644 --- a/src/Discord.Net.Core/CDN.cs +++ b/src/Discord.Net.Core/CDN.cs @@ -7,6 +7,17 @@ namespace Discord /// public static class CDN { + /// + /// Returns a team icon URL. + /// + /// The team identifier. + /// The icon identifier. + /// + /// A URL pointing to the team's icon. + /// + public static string GetTeamIconUrl(ulong teamId, string iconId) + => iconId != null ? $"{DiscordConfig.CDNUrl}team-icons/{teamId}/{iconId}.jpg" : null; + /// /// Returns an application icon URL. /// diff --git a/src/Discord.Net.Core/Entities/IApplication.cs b/src/Discord.Net.Core/Entities/IApplication.cs index 78a87dc19..2174baff9 100644 --- a/src/Discord.Net.Core/Entities/IApplication.cs +++ b/src/Discord.Net.Core/Entities/IApplication.cs @@ -22,6 +22,18 @@ namespace Discord /// Gets the icon URL of the application. /// string IconUrl { get; } + /// + /// Gets if the bot is public. + /// + bool IsBotPublic { get; } + /// + /// Gets if the bot requires code grant. + /// + bool BotRequiresCodeGrant { get; } + /// + /// Gets the team associated with this application if there is one. + /// + ITeam Team { get; } /// /// Gets the partial user object containing info on the owner of the application. diff --git a/src/Discord.Net.Core/Entities/Teams/ITeam.cs b/src/Discord.Net.Core/Entities/Teams/ITeam.cs new file mode 100644 index 000000000..5ef3e4253 --- /dev/null +++ b/src/Discord.Net.Core/Entities/Teams/ITeam.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; + +namespace Discord +{ + /// + /// Represents a Discord Team. + /// + public interface ITeam + { + /// + /// Gets the team icon url. + /// + string IconUrl { get; } + /// + /// Gets the team unique identifier. + /// + ulong Id { get; } + /// + /// Gets the members of this team. + /// + IReadOnlyList TeamMembers { get; } + /// + /// Gets the user identifier that owns this team. + /// + ulong OwnerUserId { get; } + } +} diff --git a/src/Discord.Net.Core/Entities/Teams/ITeamMember.cs b/src/Discord.Net.Core/Entities/Teams/ITeamMember.cs new file mode 100644 index 000000000..fe0e499e5 --- /dev/null +++ b/src/Discord.Net.Core/Entities/Teams/ITeamMember.cs @@ -0,0 +1,25 @@ +namespace Discord +{ + /// + /// Represents a Discord Team member. + /// + public interface ITeamMember + { + /// + /// Gets the membership state of this team member. + /// + MembershipState MembershipState { get; } + /// + /// Gets the permissions of this team member. + /// + string[] Permissions { get; } + /// + /// Gets the team unique identifier for this team member. + /// + ulong TeamId { get; } + /// + /// Gets the Discord user of this team member. + /// + IUser User { get; } + } +} diff --git a/src/Discord.Net.Core/Entities/Teams/MembershipState.cs b/src/Discord.Net.Core/Entities/Teams/MembershipState.cs new file mode 100644 index 000000000..45b1693b0 --- /dev/null +++ b/src/Discord.Net.Core/Entities/Teams/MembershipState.cs @@ -0,0 +1,11 @@ +namespace Discord +{ + /// + /// Represents the membership state of a team member. + /// + public enum MembershipState + { + Invited, + Accepted, + } +} diff --git a/src/Discord.Net.Rest/API/Common/Application.cs b/src/Discord.Net.Rest/API/Common/Application.cs index ca4c443f1..b80aecd27 100644 --- a/src/Discord.Net.Rest/API/Common/Application.cs +++ b/src/Discord.Net.Rest/API/Common/Application.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#pragma warning disable CS1591 using Newtonsoft.Json; namespace Discord.API @@ -15,6 +15,12 @@ namespace Discord.API public ulong Id { get; set; } [JsonProperty("icon")] public string Icon { get; set; } + [JsonProperty("bot_public")] + public bool IsBotPublic { get; set; } + [JsonProperty("bot_require_code_grant")] + public bool BotRequiresCodeGrant { get; set; } + [JsonProperty("team")] + public Optional Team { get; set; } [JsonProperty("flags"), Int53] public Optional Flags { get; set; } diff --git a/src/Discord.Net.Rest/API/Common/MembershipState.cs b/src/Discord.Net.Rest/API/Common/MembershipState.cs new file mode 100644 index 000000000..67fcc8908 --- /dev/null +++ b/src/Discord.Net.Rest/API/Common/MembershipState.cs @@ -0,0 +1,9 @@ +namespace Discord.API +{ + internal enum MembershipState + { + None = 0, + Invited = 1, + Accepted = 2, + } +} diff --git a/src/Discord.Net.Rest/API/Common/Team.cs b/src/Discord.Net.Rest/API/Common/Team.cs new file mode 100644 index 000000000..4910f43f7 --- /dev/null +++ b/src/Discord.Net.Rest/API/Common/Team.cs @@ -0,0 +1,17 @@ +#pragma warning disable CS1591 +using Newtonsoft.Json; + +namespace Discord.API +{ + internal class Team + { + [JsonProperty("icon")] + public Optional Icon { get; set; } + [JsonProperty("id")] + public ulong Id { get; set; } + [JsonProperty("members")] + public TeamMember[] TeamMembers { get; set; } + [JsonProperty("owner_user_id")] + public ulong OwnerUserId { get; set; } + } +} diff --git a/src/Discord.Net.Rest/API/Common/TeamMember.cs b/src/Discord.Net.Rest/API/Common/TeamMember.cs new file mode 100644 index 000000000..788f73b61 --- /dev/null +++ b/src/Discord.Net.Rest/API/Common/TeamMember.cs @@ -0,0 +1,17 @@ +#pragma warning disable CS1591 +using Newtonsoft.Json; + +namespace Discord.API +{ + internal class TeamMember + { + [JsonProperty("membership_state")] + public MembershipState MembershipState { get; set; } + [JsonProperty("permissions")] + public string[] Permissions { get; set; } + [JsonProperty("team_id")] + public ulong TeamId { get; set; } + [JsonProperty("user")] + public User User { get; set; } + } +} diff --git a/src/Discord.Net.Rest/Entities/RestApplication.cs b/src/Discord.Net.Rest/Entities/RestApplication.cs index d033978d0..6c22c0836 100644 --- a/src/Discord.Net.Rest/Entities/RestApplication.cs +++ b/src/Discord.Net.Rest/Entities/RestApplication.cs @@ -21,6 +21,12 @@ namespace Discord.Rest public string[] RPCOrigins { get; private set; } /// public ulong Flags { get; private set; } + /// + public bool IsBotPublic { get; private set; } + /// + public bool BotRequiresCodeGrant { get; private set; } + /// + public ITeam Team { get; private set; } /// public IUser Owner { get; private set; } @@ -46,11 +52,15 @@ namespace Discord.Rest RPCOrigins = model.RPCOrigins; Name = model.Name; _iconId = model.Icon; + IsBotPublic = model.IsBotPublic; + BotRequiresCodeGrant = model.BotRequiresCodeGrant; if (model.Flags.IsSpecified) Flags = model.Flags.Value; //TODO: Do we still need this? if (model.Owner.IsSpecified) Owner = RestUser.Create(Discord, model.Owner.Value); + if (model.Team.IsSpecified) + Team = RestTeam.Create(Discord, model.Team.Value); } /// Unable to update this object from a different application token. diff --git a/src/Discord.Net.Rest/Entities/Teams/RestTeam.cs b/src/Discord.Net.Rest/Entities/Teams/RestTeam.cs new file mode 100644 index 000000000..2343f8b5d --- /dev/null +++ b/src/Discord.Net.Rest/Entities/Teams/RestTeam.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Model = Discord.API.Team; + +namespace Discord.Rest +{ + public class RestTeam : RestEntity, ITeam + { + /// + public string IconUrl => _iconId != null ? CDN.GetTeamIconUrl(Id, _iconId) : null; + /// + public IReadOnlyList TeamMembers { get; private set; } + /// + public ulong OwnerUserId { get; private set; } + + private string _iconId; + + internal RestTeam(BaseDiscordClient discord, ulong id) + : base(discord, id) + { + } + internal static RestTeam Create(BaseDiscordClient discord, Model model) + { + var entity = new RestTeam(discord, model.Id); + entity.Update(model); + return entity; + } + internal virtual void Update(Model model) + { + if (model.Icon.IsSpecified) + _iconId = model.Icon.Value; + OwnerUserId = model.OwnerUserId; + TeamMembers = model.TeamMembers.Select(x => new RestTeamMember(Discord, x)).ToImmutableArray(); + } + } +} diff --git a/src/Discord.Net.Rest/Entities/Teams/RestTeamMember.cs b/src/Discord.Net.Rest/Entities/Teams/RestTeamMember.cs new file mode 100644 index 000000000..322bb6a3f --- /dev/null +++ b/src/Discord.Net.Rest/Entities/Teams/RestTeamMember.cs @@ -0,0 +1,30 @@ +using System; +using Model = Discord.API.TeamMember; + +namespace Discord.Rest +{ + public class RestTeamMember : ITeamMember + { + /// + public MembershipState MembershipState { get; } + /// + public string[] Permissions { get; } + /// + public ulong TeamId { get; } + /// + public IUser User { get; } + + internal RestTeamMember(BaseDiscordClient discord, Model model) + { + MembershipState = model.MembershipState switch + { + API.MembershipState.Invited => MembershipState.Invited, + API.MembershipState.Accepted => MembershipState.Accepted, + _ => throw new InvalidOperationException("Invalid membership state"), + }; + Permissions = model.Permissions; + TeamId = model.TeamId; + User = RestUser.Create(discord, model.User); + } + } +} From 1e012ac0b822129e59d6e9132a836453d181aae9 Mon Sep 17 00:00:00 2001 From: Jack Fox <0xdeadbeef1@gmail.com> Date: Sun, 8 Nov 2020 16:21:51 -0500 Subject: [PATCH 09/14] feature: Add GetStreams to AudioClient (#1588) * Added GetStreams * Change return type * Change return type on the interface Co-authored-by: Paulo --- src/Discord.Net.Core/Audio/IAudioClient.cs | 6 +++++- src/Discord.Net.WebSocket/Audio/AudioClient.cs | 8 +++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/Discord.Net.Core/Audio/IAudioClient.cs b/src/Discord.Net.Core/Audio/IAudioClient.cs index 018c8bc05..2fc52a529 100644 --- a/src/Discord.Net.Core/Audio/IAudioClient.cs +++ b/src/Discord.Net.Core/Audio/IAudioClient.cs @@ -1,4 +1,5 @@ -using System; +using System; +using System.Collections.Generic; using System.Threading.Tasks; namespace Discord.Audio @@ -20,6 +21,9 @@ namespace Discord.Audio /// Gets the estimated round-trip latency, in milliseconds, to the voice UDP server. int UdpLatency { get; } + /// Gets the current audio streams. + IReadOnlyDictionary GetStreams(); + Task StopAsync(); Task SetSpeakingAsync(bool value); diff --git a/src/Discord.Net.WebSocket/Audio/AudioClient.cs b/src/Discord.Net.WebSocket/Audio/AudioClient.cs index 2210e019f..3549fb106 100644 --- a/src/Discord.Net.WebSocket/Audio/AudioClient.cs +++ b/src/Discord.Net.WebSocket/Audio/AudioClient.cs @@ -99,6 +99,12 @@ namespace Discord.Audio _token = token; await _connection.StartAsync().ConfigureAwait(false); } + + public IReadOnlyDictionary GetStreams() + { + return _streams.ToDictionary(pair => pair.Key, pair => pair.Value.Reader); + } + public async Task StopAsync() { await _connection.StopAsync().ConfigureAwait(false); @@ -379,7 +385,7 @@ namespace Discord.Audio private async Task RunHeartbeatAsync(int intervalMillis, CancellationToken cancelToken) { - //TODO: Clean this up when Discord's session patch is live + // TODO: Clean this up when Discord's session patch is live try { await _audioLogger.DebugAsync("Heartbeat Started").ConfigureAwait(false); From 913444349465c339f0624ef0ea26715d9e7a1853 Mon Sep 17 00:00:00 2001 From: Paulo Date: Sun, 8 Nov 2020 19:29:15 -0300 Subject: [PATCH 10/14] fix: Crosspost throwing InvalidOperationException (#1671) * Add INewsChannel * Renaming variable to match the new type --- src/Discord.Net.Core/Entities/Channels/INewsChannel.cs | 9 +++++++++ .../Entities/Channels/RestNewsChannel.cs | 2 +- .../Entities/Messages/RestUserMessage.cs | 4 ++-- .../Entities/Channels/SocketNewsChannel.cs | 2 +- .../Entities/Invites/SocketInvite.cs | 2 +- .../Entities/Messages/SocketUserMessage.cs | 4 ++-- 6 files changed, 16 insertions(+), 7 deletions(-) create mode 100644 src/Discord.Net.Core/Entities/Channels/INewsChannel.cs diff --git a/src/Discord.Net.Core/Entities/Channels/INewsChannel.cs b/src/Discord.Net.Core/Entities/Channels/INewsChannel.cs new file mode 100644 index 000000000..a1223b48b --- /dev/null +++ b/src/Discord.Net.Core/Entities/Channels/INewsChannel.cs @@ -0,0 +1,9 @@ +namespace Discord +{ + /// + /// Represents a generic news channel in a guild that can send and receive messages. + /// + public interface INewsChannel : ITextChannel + { + } +} diff --git a/src/Discord.Net.Rest/Entities/Channels/RestNewsChannel.cs b/src/Discord.Net.Rest/Entities/Channels/RestNewsChannel.cs index 8a334fae5..fad3358dc 100644 --- a/src/Discord.Net.Rest/Entities/Channels/RestNewsChannel.cs +++ b/src/Discord.Net.Rest/Entities/Channels/RestNewsChannel.cs @@ -12,7 +12,7 @@ namespace Discord.Rest /// Represents a REST-based news channel in a guild that has the same properties as a . /// [DebuggerDisplay(@"{DebuggerDisplay,nq}")] - public class RestNewsChannel : RestTextChannel + public class RestNewsChannel : RestTextChannel, INewsChannel { internal RestNewsChannel(BaseDiscordClient discord, IGuild guild, ulong id) :base(discord, guild, id) diff --git a/src/Discord.Net.Rest/Entities/Messages/RestUserMessage.cs b/src/Discord.Net.Rest/Entities/Messages/RestUserMessage.cs index be955b13d..79df4308d 100644 --- a/src/Discord.Net.Rest/Entities/Messages/RestUserMessage.cs +++ b/src/Discord.Net.Rest/Entities/Messages/RestUserMessage.cs @@ -154,10 +154,10 @@ namespace Discord.Rest => MentionUtils.Resolve(this, 0, userHandling, channelHandling, roleHandling, everyoneHandling, emojiHandling); /// - /// This operation may only be called on a channel. + /// This operation may only be called on a channel. public async Task CrosspostAsync(RequestOptions options = null) { - if (!(Channel is RestNewsChannel)) + if (!(Channel is INewsChannel)) { throw new InvalidOperationException("Publishing (crossposting) is only valid in news channels."); } diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketNewsChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketNewsChannel.cs index 815a99ce7..944dd2d7f 100644 --- a/src/Discord.Net.WebSocket/Entities/Channels/SocketNewsChannel.cs +++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketNewsChannel.cs @@ -15,7 +15,7 @@ namespace Discord.WebSocket /// /// [DebuggerDisplay(@"{DebuggerDisplay,nq}")] - public class SocketNewsChannel : SocketTextChannel + public class SocketNewsChannel : SocketTextChannel, INewsChannel { internal SocketNewsChannel(DiscordSocketClient discord, ulong id, SocketGuild guild) :base(discord, id, guild) diff --git a/src/Discord.Net.WebSocket/Entities/Invites/SocketInvite.cs b/src/Discord.Net.WebSocket/Entities/Invites/SocketInvite.cs index fa8c56599..902f13935 100644 --- a/src/Discord.Net.WebSocket/Entities/Invites/SocketInvite.cs +++ b/src/Discord.Net.WebSocket/Entities/Invites/SocketInvite.cs @@ -34,7 +34,7 @@ namespace Discord.WebSocket case ICategoryChannel categoryChannel: return ChannelType.Category; case IDMChannel dmChannel: return ChannelType.DM; case IGroupChannel groupChannel: return ChannelType.Group; - case SocketNewsChannel socketNewsChannel: return ChannelType.News; + case INewsChannel newsChannel: return ChannelType.News; case ITextChannel textChannel: return ChannelType.Text; default: throw new InvalidOperationException("Invalid channel type."); } diff --git a/src/Discord.Net.WebSocket/Entities/Messages/SocketUserMessage.cs b/src/Discord.Net.WebSocket/Entities/Messages/SocketUserMessage.cs index 51b0c2043..da7f8f16b 100644 --- a/src/Discord.Net.WebSocket/Entities/Messages/SocketUserMessage.cs +++ b/src/Discord.Net.WebSocket/Entities/Messages/SocketUserMessage.cs @@ -158,10 +158,10 @@ namespace Discord.WebSocket => MentionUtils.Resolve(this, 0, userHandling, channelHandling, roleHandling, everyoneHandling, emojiHandling); /// - /// This operation may only be called on a channel. + /// This operation may only be called on a channel. public async Task CrosspostAsync(RequestOptions options = null) { - if (!(Channel is SocketNewsChannel)) + if (!(Channel is INewsChannel)) { throw new InvalidOperationException("Publishing (crossposting) is only valid in news channels."); } From 05a1f0a709e6970f4302d9954a94b3a88bf01e6c Mon Sep 17 00:00:00 2001 From: Paulo Date: Mon, 9 Nov 2020 12:31:17 -0300 Subject: [PATCH 11/14] fix: Discord sends null when there's no team --- src/Discord.Net.Rest/Entities/RestApplication.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Discord.Net.Rest/Entities/RestApplication.cs b/src/Discord.Net.Rest/Entities/RestApplication.cs index 6c22c0836..d96d837ab 100644 --- a/src/Discord.Net.Rest/Entities/RestApplication.cs +++ b/src/Discord.Net.Rest/Entities/RestApplication.cs @@ -59,7 +59,7 @@ namespace Discord.Rest Flags = model.Flags.Value; //TODO: Do we still need this? if (model.Owner.IsSpecified) Owner = RestUser.Create(Discord, model.Owner.Value); - if (model.Team.IsSpecified) + if (model.Team.IsSpecified && model.Team.Value != null) Team = RestTeam.Create(Discord, model.Team.Value); } From be60d813f77ddfb2f131ae4f290026f3ff2756ad Mon Sep 17 00:00:00 2001 From: Paulo Date: Mon, 9 Nov 2020 15:39:08 -0300 Subject: [PATCH 12/14] fix: Team is nullable, not optional (#1672) --- src/Discord.Net.Rest/API/Common/Application.cs | 2 +- src/Discord.Net.Rest/Entities/RestApplication.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Discord.Net.Rest/API/Common/Application.cs b/src/Discord.Net.Rest/API/Common/Application.cs index b80aecd27..aba3e524b 100644 --- a/src/Discord.Net.Rest/API/Common/Application.cs +++ b/src/Discord.Net.Rest/API/Common/Application.cs @@ -20,7 +20,7 @@ namespace Discord.API [JsonProperty("bot_require_code_grant")] public bool BotRequiresCodeGrant { get; set; } [JsonProperty("team")] - public Optional Team { get; set; } + public Team Team { get; set; } [JsonProperty("flags"), Int53] public Optional Flags { get; set; } diff --git a/src/Discord.Net.Rest/Entities/RestApplication.cs b/src/Discord.Net.Rest/Entities/RestApplication.cs index d96d837ab..5c2f872cf 100644 --- a/src/Discord.Net.Rest/Entities/RestApplication.cs +++ b/src/Discord.Net.Rest/Entities/RestApplication.cs @@ -59,8 +59,8 @@ namespace Discord.Rest Flags = model.Flags.Value; //TODO: Do we still need this? if (model.Owner.IsSpecified) Owner = RestUser.Create(Discord, model.Owner.Value); - if (model.Team.IsSpecified && model.Team.Value != null) - Team = RestTeam.Create(Discord, model.Team.Value); + if (model.Team != null) + Team = RestTeam.Create(Discord, model.Team); } /// Unable to update this object from a different application token. From 47ed8064180420d2109e23794270cd4246161ffe Mon Sep 17 00:00:00 2001 From: Paulo Date: Sun, 15 Nov 2020 13:20:08 -0300 Subject: [PATCH 13/14] misc: Change ratelimit messages (#1678) --- src/Discord.Net.Rest/BaseDiscordClient.cs | 6 +++--- src/Discord.Net.Rest/Net/Queue/RequestQueue.cs | 6 +++--- src/Discord.Net.Rest/Net/Queue/RequestQueueBucket.cs | 4 ++-- src/Discord.Net.Webhook/DiscordWebhookClient.cs | 6 +++--- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Discord.Net.Rest/BaseDiscordClient.cs b/src/Discord.Net.Rest/BaseDiscordClient.cs index 58b42929a..b641fa1c3 100644 --- a/src/Discord.Net.Rest/BaseDiscordClient.cs +++ b/src/Discord.Net.Rest/BaseDiscordClient.cs @@ -46,12 +46,12 @@ namespace Discord.Rest _restLogger = LogManager.CreateLogger("Rest"); _isFirstLogin = config.DisplayInitialLog; - ApiClient.RequestQueue.RateLimitTriggered += async (id, info) => + ApiClient.RequestQueue.RateLimitTriggered += async (id, info, endpoint) => { if (info == null) - await _restLogger.VerboseAsync($"Preemptive Rate limit triggered: {id?.ToString() ?? "null"}").ConfigureAwait(false); + await _restLogger.VerboseAsync($"Preemptive Rate limit triggered: {endpoint} {(id.IsHashBucket ? $"(Bucket: {id.BucketHash})" : "")}").ConfigureAwait(false); else - await _restLogger.WarningAsync($"Rate limit triggered: {id?.ToString() ?? "null"}").ConfigureAwait(false); + await _restLogger.WarningAsync($"Rate limit triggered: {endpoint} {(id.IsHashBucket ? $"(Bucket: {id.BucketHash})" : "")}").ConfigureAwait(false); }; ApiClient.SentRequest += async (method, endpoint, millis) => await _restLogger.VerboseAsync($"{method} {endpoint}: {millis} ms").ConfigureAwait(false); } diff --git a/src/Discord.Net.Rest/Net/Queue/RequestQueue.cs b/src/Discord.Net.Rest/Net/Queue/RequestQueue.cs index 691ac77c0..127a48cf3 100644 --- a/src/Discord.Net.Rest/Net/Queue/RequestQueue.cs +++ b/src/Discord.Net.Rest/Net/Queue/RequestQueue.cs @@ -12,7 +12,7 @@ namespace Discord.Net.Queue { internal class RequestQueue : IDisposable { - public event Func RateLimitTriggered; + public event Func RateLimitTriggered; private readonly ConcurrentDictionary _buckets; private readonly SemaphoreSlim _tokenLock; @@ -121,9 +121,9 @@ namespace Discord.Net.Queue } return (RequestBucket)obj; } - internal async Task RaiseRateLimitTriggered(BucketId bucketId, RateLimitInfo? info) + internal async Task RaiseRateLimitTriggered(BucketId bucketId, RateLimitInfo? info, string endpoint) { - await RateLimitTriggered(bucketId, info).ConfigureAwait(false); + await RateLimitTriggered(bucketId, info, endpoint).ConfigureAwait(false); } internal (RequestBucket, BucketId) UpdateBucketHash(BucketId id, string discordHash) { diff --git a/src/Discord.Net.Rest/Net/Queue/RequestQueueBucket.cs b/src/Discord.Net.Rest/Net/Queue/RequestQueueBucket.cs index f1471d545..edd55f158 100644 --- a/src/Discord.Net.Rest/Net/Queue/RequestQueueBucket.cs +++ b/src/Discord.Net.Rest/Net/Queue/RequestQueueBucket.cs @@ -84,7 +84,7 @@ namespace Discord.Net.Queue #endif UpdateRateLimit(id, request, info, true); } - await _queue.RaiseRateLimitTriggered(Id, info).ConfigureAwait(false); + await _queue.RaiseRateLimitTriggered(Id, info, $"{request.Method} {request.Endpoint}").ConfigureAwait(false); continue; //Retry case HttpStatusCode.BadGateway: //502 #if DEBUG_LIMITS @@ -187,7 +187,7 @@ namespace Discord.Net.Queue if (!isRateLimited) { isRateLimited = true; - await _queue.RaiseRateLimitTriggered(Id, null).ConfigureAwait(false); + await _queue.RaiseRateLimitTriggered(Id, null, $"{request.Method} {request.Endpoint}").ConfigureAwait(false); } ThrowRetryLimit(request); diff --git a/src/Discord.Net.Webhook/DiscordWebhookClient.cs b/src/Discord.Net.Webhook/DiscordWebhookClient.cs index 9c9bfe958..a6d4ef183 100644 --- a/src/Discord.Net.Webhook/DiscordWebhookClient.cs +++ b/src/Discord.Net.Webhook/DiscordWebhookClient.cs @@ -74,12 +74,12 @@ namespace Discord.Webhook _restLogger = LogManager.CreateLogger("Rest"); - ApiClient.RequestQueue.RateLimitTriggered += async (id, info) => + ApiClient.RequestQueue.RateLimitTriggered += async (id, info, endpoint) => { if (info == null) - await _restLogger.VerboseAsync($"Preemptive Rate limit triggered: {id?.ToString() ?? "null"}").ConfigureAwait(false); + await _restLogger.VerboseAsync($"Preemptive Rate limit triggered: {endpoint} {(id.IsHashBucket ? $"(Bucket: {id.BucketHash})" : "")}").ConfigureAwait(false); else - await _restLogger.WarningAsync($"Rate limit triggered: {id?.ToString() ?? "null"}").ConfigureAwait(false); + await _restLogger.WarningAsync($"Rate limit triggered: {endpoint} {(id.IsHashBucket ? $"(Bucket: {id.BucketHash})" : "")}").ConfigureAwait(false); }; ApiClient.SentRequest += async (method, endpoint, millis) => await _restLogger.VerboseAsync($"{method} {endpoint}: {millis} ms").ConfigureAwait(false); } From 3a1001830bbf699aff3e524a8eb2d55a886227cb Mon Sep 17 00:00:00 2001 From: Paulo Date: Tue, 17 Nov 2020 02:11:02 -0300 Subject: [PATCH 14/14] misc: Missing summary tag --- src/Discord.Net.WebSocket/DiscordSocketConfig.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Discord.Net.WebSocket/DiscordSocketConfig.cs b/src/Discord.Net.WebSocket/DiscordSocketConfig.cs index 11e44d8dc..0e8fbe73f 100644 --- a/src/Discord.Net.WebSocket/DiscordSocketConfig.cs +++ b/src/Discord.Net.WebSocket/DiscordSocketConfig.cs @@ -151,6 +151,7 @@ namespace Discord.WebSocket } private int _maxWaitForGuildAvailable = 10000; + /// /// Gets or sets gateway intents to limit what events are sent from Discord. Allows for more granular control than the property. /// ///