Skip to content

Commit

Permalink
[Fix] NRE in message commands in user app contexts (#3035)
Browse files Browse the repository at this point in the history
* bump few more things

* expose `MentionedRoleIds` on `SocketMessage` + add some syntax sugar

* right, we can't have nice things cuz netfx

* omfg that's an I/O operation in ctor bruh
  • Loading branch information
Misha-133 authored Dec 4, 2024
1 parent d5879c8 commit c78296f
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 30 deletions.
2 changes: 1 addition & 1 deletion src/Discord.Net.Commands/Discord.Net.Commands.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.0" />
</ItemGroup>
</Project>
25 changes: 16 additions & 9 deletions src/Discord.Net.WebSocket/Entities/Messages/SocketMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ public abstract class SocketMessage : SocketEntity<ulong>, IMessage
{
#region SocketMessage
private long _timestampTicks;
private readonly List<SocketReaction> _reactions = new List<SocketReaction>();
private ImmutableArray<SocketUser> _userMentions = ImmutableArray.Create<SocketUser>();
private readonly List<SocketReaction> _reactions = [];
private ImmutableArray<SocketUser> _userMentions = [];

/// <summary>
/// Gets the author of this message.
Expand Down Expand Up @@ -113,18 +113,26 @@ public abstract class SocketMessage : SocketEntity<ulong>, IMessage
/// <returns>
/// Collection of WebSocket-based guild channels.
/// </returns>
public virtual IReadOnlyCollection<SocketGuildChannel> MentionedChannels => ImmutableArray.Create<SocketGuildChannel>();
public virtual IReadOnlyCollection<SocketGuildChannel> MentionedChannels => [];
/// <summary>
/// Returns the roles mentioned in this message.
/// </summary>
/// <remarks>
/// This collection may be missing values due to the guild being missing from cache (i.e. in user app interaction context).
/// In that case you can use the <see cref="MentionedRoleIds"/> property.
/// </remarks>
/// <returns>
/// Collection of WebSocket-based roles.
/// </returns>
public virtual IReadOnlyCollection<SocketRole> MentionedRoles => ImmutableArray.Create<SocketRole>();
public virtual IReadOnlyCollection<SocketRole> MentionedRoles => [];

/// <inheritdoc />
public virtual IReadOnlyCollection<ulong> MentionedRoleIds => [];

/// <inheritdoc />
public virtual IReadOnlyCollection<ITag> Tags => ImmutableArray.Create<ITag>();
public virtual IReadOnlyCollection<ITag> Tags => [];
/// <inheritdoc />
public virtual IReadOnlyCollection<SocketSticker> Stickers => ImmutableArray.Create<SocketSticker>();
public virtual IReadOnlyCollection<SocketSticker> Stickers => [];
/// <inheritdoc />
public IReadOnlyDictionary<IEmote, ReactionMetadata> Reactions => _reactions.GroupBy(r => r.Emote).ToDictionary(x => x.Key, x => new ReactionMetadata { ReactionCount = x.Count(), IsMe = x.Any(y => y.UserId == Discord.CurrentUser.Id) });
/// <summary>
Expand Down Expand Up @@ -271,7 +279,8 @@ internal virtual void Update(ClientState state, Model model)
var val = value[i];
if (val != null)
{
var user = Channel.GetUserAsync(val.Id, CacheMode.CacheOnly).GetAwaiter().GetResult() as SocketUser;
// TODO: this is cursed af and should be yeeted
var user = Channel?.GetUserAsync(val.Id, CacheMode.CacheOnly).GetAwaiter().GetResult() as SocketUser;
if (user != null)
newMentions.Add(user);
else
Expand Down Expand Up @@ -346,8 +355,6 @@ public Task DeleteAsync(RequestOptions options = null)
/// <inheritdoc />
IReadOnlyCollection<ulong> IMessage.MentionedChannelIds => MentionedChannels.Select(x => x.Id).ToImmutableArray();
/// <inheritdoc />
IReadOnlyCollection<ulong> IMessage.MentionedRoleIds => MentionedRoles.Select(x => x.Id).ToImmutableArray();
/// <inheritdoc />
IReadOnlyCollection<ulong> IMessage.MentionedUserIds => MentionedUsers.Select(x => x.Id).ToImmutableArray();

/// <inheritdoc/>
Expand Down
40 changes: 24 additions & 16 deletions src/Discord.Net.WebSocket/Entities/Messages/SocketUserMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@ public class SocketUserMessage : SocketMessage, IUserMessage
private bool _isMentioningEveryone, _isTTS, _isPinned;
private long? _editedTimestampTicks;
private IUserMessage _referencedMessage;
private ImmutableArray<Attachment> _attachments = ImmutableArray.Create<Attachment>();
private ImmutableArray<Embed> _embeds = ImmutableArray.Create<Embed>();
private ImmutableArray<ITag> _tags = ImmutableArray.Create<ITag>();
private ImmutableArray<SocketRole> _roleMentions = ImmutableArray.Create<SocketRole>();
private ImmutableArray<SocketSticker> _stickers = ImmutableArray.Create<SocketSticker>();
private ImmutableArray<Attachment> _attachments = [];
private ImmutableArray<Embed> _embeds = [];
private ImmutableArray<ITag> _tags = [];
private ImmutableArray<SocketRole> _roleMentions;
private ImmutableArray<ulong> _roleMentionsIds = [];
private ImmutableArray<SocketSticker> _stickers = [];

/// <inheritdoc />
public override bool IsTTS => _isTTS;
Expand All @@ -44,6 +45,9 @@ public class SocketUserMessage : SocketMessage, IUserMessage
public override IReadOnlyCollection<SocketGuildChannel> MentionedChannels => MessageHelper.FilterTagsByValue<SocketGuildChannel>(TagType.ChannelMention, _tags);
/// <inheritdoc />
public override IReadOnlyCollection<SocketRole> MentionedRoles => _roleMentions;
/// <inheritdoc />
public override IReadOnlyCollection<ulong> MentionedRoleIds => _roleMentionsIds;

/// <inheritdoc />
public override IReadOnlyCollection<SocketSticker> Stickers => _stickers;
/// <inheritdoc />
Expand All @@ -64,6 +68,7 @@ public class SocketUserMessage : SocketMessage, IUserMessage
internal SocketUserMessage(DiscordSocketClient discord, ulong id, ISocketMessageChannel channel, SocketUser author, MessageSource source)
: base(discord, id, channel, author, source)
{
_roleMentions = ImmutableArray.Create<SocketRole>();
}
internal new static SocketUserMessage Create(DiscordSocketClient discord, ClientState state, SocketUser author, ISocketMessageChannel channel, Model model)
{
Expand All @@ -87,7 +92,12 @@ internal override void Update(ClientState state, Model model)
if (model.MentionEveryone.IsSpecified)
_isMentioningEveryone = model.MentionEveryone.Value;
if (model.RoleMentions.IsSpecified)
_roleMentions = model.RoleMentions.Value.Select(x => guild.GetRole(x)).ToImmutableArray();
{
if (guild is not null)
_roleMentions = model.RoleMentions.Value.Select(x => guild.GetRole(x)).ToImmutableArray();
_roleMentionsIds = model.RoleMentions.Value.ToImmutableArray();
}


if (model.Attachments.IsSpecified)
{
Expand All @@ -100,7 +110,7 @@ internal override void Update(ClientState state, Model model)
_attachments = attachments.ToImmutable();
}
else
_attachments = ImmutableArray.Create<Attachment>();
_attachments = [];
}

if (model.Embeds.IsSpecified)
Expand All @@ -114,7 +124,7 @@ internal override void Update(ClientState state, Model model)
_embeds = embeds.ToImmutable();
}
else
_embeds = ImmutableArray.Create<Embed>();
_embeds = [];
}

if (model.Content.IsSpecified)
Expand Down Expand Up @@ -155,34 +165,32 @@ internal override void Update(ClientState state, Model model)
if (value.Length > 0)
{
var stickers = ImmutableArray.CreateBuilder<SocketSticker>(value.Length);
for (int i = 0; i < value.Length; i++)
foreach (var stickerItem in value)
{
var stickerItem = value[i];
SocketSticker sticker = null;

if (guild != null)
sticker = guild.GetSticker(stickerItem.Id);

if (sticker == null)
sticker = Discord.GetSticker(stickerItem.Id);
sticker ??= Discord.GetSticker(stickerItem.Id);

// if they want to auto resolve
if (Discord.AlwaysResolveStickers)
{
sticker = Task.Run(async () => await Discord.GetStickerAsync(stickerItem.Id).ConfigureAwait(false)).GetAwaiter().GetResult();
var item = stickerItem;
sticker = Task.Run(async () => await Discord.GetStickerAsync(item.Id).ConfigureAwait(false)).GetAwaiter().GetResult();
}

// if its still null, create an unknown
if (sticker == null)
sticker = SocketUnknownSticker.Create(Discord, stickerItem);
sticker ??= SocketUnknownSticker.Create(Discord, stickerItem);

stickers.Add(sticker);
}

_stickers = stickers.ToImmutable();
}
else
_stickers = ImmutableArray.Create<SocketSticker>();
_stickers = [];
}

if (model.Resolved.IsSpecified)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="FluentAssertions" Version="7.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>
Expand Down
4 changes: 2 additions & 2 deletions test/Discord.Net.Tests.Unit/Discord.Net.Tests.Unit.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
<ProjectReference Include="../../src/Discord.Net.WebSocket/Discord.Net.WebSocket.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="FluentAssertions" Version="7.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
Expand Down

0 comments on commit c78296f

Please sign in to comment.