Skip to content

Commit

Permalink
Update socket presence and add new presence event (#1945)
Browse files Browse the repository at this point in the history
  • Loading branch information
quinchs committed Nov 25, 2021
1 parent 10afd96 commit 9d6dc62
Show file tree
Hide file tree
Showing 8 changed files with 64 additions and 37 deletions.
6 changes: 3 additions & 3 deletions src/Discord.Net.Core/Entities/Users/IPresence.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Collections.Immutable;
using System.Collections.Generic;

namespace Discord
{
Expand All @@ -14,10 +14,10 @@ public interface IPresence
/// <summary>
/// Gets the set of clients where this user is currently active.
/// </summary>
IImmutableSet<ClientType> ActiveClients { get; }
IReadOnlyCollection<ClientType> ActiveClients { get; }
/// <summary>
/// Gets the list of activities that this user currently has available.
/// </summary>
IImmutableList<IActivity> Activities { get; }
IReadOnlyCollection<IActivity> Activities { get; }
}
}
5 changes: 3 additions & 2 deletions src/Discord.Net.Rest/Entities/Users/RestUser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Threading.Tasks;
using Model = Discord.API.User;
using EventUserModel = Discord.API.GuildScheduledEventUser;
using System.Collections.Generic;

namespace Discord.Rest
{
Expand Down Expand Up @@ -41,9 +42,9 @@ public class RestUser : RestEntity<ulong>, IUser, IUpdateable
/// <inheritdoc />
public virtual UserStatus Status => UserStatus.Offline;
/// <inheritdoc />
public virtual IImmutableSet<ClientType> ActiveClients => ImmutableHashSet<ClientType>.Empty;
public virtual IReadOnlyCollection<ClientType> ActiveClients => ImmutableHashSet<ClientType>.Empty;
/// <inheritdoc />
public virtual IImmutableList<IActivity> Activities => ImmutableList<IActivity>.Empty;
public virtual IReadOnlyCollection<IActivity> Activities => ImmutableList<IActivity>.Empty;
/// <inheritdoc />
public virtual bool IsWebhook => false;

Expand Down
12 changes: 12 additions & 0 deletions src/Discord.Net.WebSocket/BaseSocketClient.Events.cs
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,18 @@ public partial class BaseSocketClient
internal readonly AsyncEvent<Func<SocketGroupUser, Task>> _recipientRemovedEvent = new AsyncEvent<Func<SocketGroupUser, Task>>();
#endregion

#region Presence

/// <summary> Fired when a users presence is updated. </summary>
public event Func<SocketUser, SocketPresence, SocketPresence, Task> PresenceUpdated
{
add { _presenceUpdated.Add(value); }
remove { _presenceUpdated.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketUser, SocketPresence, SocketPresence, Task>> _presenceUpdated = new AsyncEvent<Func<SocketUser, SocketPresence, SocketPresence, Task>>();

#endregion

#region Invites
/// <summary>
/// Fired when an invite is created.
Expand Down
23 changes: 10 additions & 13 deletions src/Discord.Net.WebSocket/DiscordSocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1858,6 +1858,8 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty

var data = (payload as JToken).ToObject<API.Presence>(_serializer);

SocketUser user = null;

if (data.GuildId.IsSpecified)
{
var guild = State.GetGuild(data.GuildId.Value);
Expand All @@ -1872,7 +1874,7 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty
return;
}

var user = guild.GetUser(data.User.Id);
user = guild.GetUser(data.User.Id);
if (user == null)
{
if (data.Status == UserStatus.Offline)
Expand All @@ -1890,26 +1892,21 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty
await TimedInvokeAsync(_userUpdatedEvent, nameof(UserUpdated), globalBefore, user).ConfigureAwait(false);
}
}

var before = user.Clone();
user.Update(State, data, true);
var cacheableBefore = new Cacheable<SocketGuildUser, ulong>(before, user.Id, true, () => Task.FromResult(user));
await TimedInvokeAsync(_guildMemberUpdatedEvent, nameof(GuildMemberUpdated), cacheableBefore, user).ConfigureAwait(false);
}
else
{
var globalUser = State.GetUser(data.User.Id);
if (globalUser == null)
user = State.GetUser(data.User.Id);
if (user == null)
{
await UnknownGlobalUserAsync(type, data.User.Id).ConfigureAwait(false);
return;
}

var before = globalUser.Clone();
globalUser.Update(State, data.User);
globalUser.Update(State, data);
await TimedInvokeAsync(_userUpdatedEvent, nameof(UserUpdated), before, globalUser).ConfigureAwait(false);
}

var before = user.Presence.Clone();
user.Update(State, data.User);
user.Update(data);
await TimedInvokeAsync(_presenceUpdated, nameof(PresenceUpdated), user, before, user.Presence).ConfigureAwait(false);
}
break;
case "TYPING_START":
Expand Down
6 changes: 0 additions & 6 deletions src/Discord.Net.WebSocket/Entities/Users/SocketGlobalUser.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Diagnostics;
using System.Linq;
using Model = Discord.API.User;
using PresenceModel = Discord.API.Presence;

namespace Discord.WebSocket
{
Expand Down Expand Up @@ -48,11 +47,6 @@ internal void RemoveRef(DiscordSocketClient discord)
}
}

internal void Update(ClientState state, PresenceModel model)
{
Presence = SocketPresence.Create(model);
}

private string DebuggerDisplay => $"{Username}#{Discriminator} ({Id}{(IsBot ? ", Bot" : "")}, Global)";
internal new SocketGlobalUser Clone() => MemberwiseClone() as SocketGlobalUser;
}
Expand Down
10 changes: 8 additions & 2 deletions src/Discord.Net.WebSocket/Entities/Users/SocketGuildUser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,7 @@ internal void Update(ClientState state, PresenceModel model, bool updatePresence
{
if (updatePresence)
{
Presence = SocketPresence.Create(model);
GlobalUser.Update(state, model);
Update(model);
}
if (model.Nick.IsSpecified)
Nickname = model.Nick.Value;
Expand All @@ -174,6 +173,13 @@ internal void Update(ClientState state, PresenceModel model, bool updatePresence
if (model.PremiumSince.IsSpecified)
_premiumSinceTicks = model.PremiumSince.Value?.UtcTicks;
}

internal override void Update(PresenceModel model)
{
Presence.Update(model);
GlobalUser.Update(model);
}

private void UpdateRoles(ulong[] roleIds)
{
var roles = ImmutableArray.CreateBuilder<ulong>(roleIds.Length + 1);
Expand Down
29 changes: 20 additions & 9 deletions src/Discord.Net.WebSocket/Entities/Users/SocketPresence.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,37 @@ namespace Discord.WebSocket
/// Represents the WebSocket user's presence status. This may include their online status and their activity.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public struct SocketPresence : IPresence
public class SocketPresence : IPresence
{
/// <inheritdoc />
public UserStatus Status { get; }
public UserStatus Status { get; private set; }
/// <inheritdoc />
public IImmutableSet<ClientType> ActiveClients { get; }
public IReadOnlyCollection<ClientType> ActiveClients { get; private set; }
/// <inheritdoc />
public IImmutableList<IActivity> Activities { get; }
public IReadOnlyCollection<IActivity> Activities { get; private set; }

internal SocketPresence() { }
internal SocketPresence(UserStatus status, IImmutableSet<ClientType> activeClients, IImmutableList<IActivity> activities)
{
Status = status;
ActiveClients = activeClients ?? ImmutableHashSet<ClientType>.Empty;
Activities = activities ?? ImmutableList<IActivity>.Empty;
}

internal static SocketPresence Create(Model model)
{
var clients = ConvertClientTypesDict(model.ClientStatus.GetValueOrDefault());
var activities = ConvertActivitiesList(model.Activities);
return new SocketPresence(model.Status, clients, activities);
var entity = new SocketPresence();
entity.Update(model);
return entity;
}

internal void Update(Model model)
{
Status = model.Status;
ActiveClients = ConvertClientTypesDict(model.ClientStatus.GetValueOrDefault()) ?? ImmutableArray<ClientType>.Empty;
Activities = ConvertActivitiesList(model.Activities) ?? ImmutableArray<IActivity>.Empty;
}

/// <summary>
/// Creates a new <see cref="IReadOnlyCollection{T}"/> containing all of the client types
/// where a user is active from the data supplied in the Presence update frame.
Expand All @@ -42,7 +53,7 @@ internal static SocketPresence Create(Model model)
/// <returns>
/// A collection of all <see cref="ClientType"/>s that this user is active.
/// </returns>
private static IImmutableSet<ClientType> ConvertClientTypesDict(IDictionary<string, string> clientTypesDict)
private static IReadOnlyCollection<ClientType> ConvertClientTypesDict(IDictionary<string, string> clientTypesDict)
{
if (clientTypesDict == null || clientTypesDict.Count == 0)
return ImmutableHashSet<ClientType>.Empty;
Expand Down Expand Up @@ -84,6 +95,6 @@ private static IImmutableList<IActivity> ConvertActivitiesList(IList<API.Game> a
public override string ToString() => Status.ToString();
private string DebuggerDisplay => $"{Status}{(Activities?.FirstOrDefault()?.Name ?? "")}";

internal SocketPresence Clone() => this;
internal SocketPresence Clone() => MemberwiseClone() as SocketPresence;
}
}
10 changes: 8 additions & 2 deletions src/Discord.Net.WebSocket/Entities/Users/SocketUser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Threading.Tasks;
using Discord.Rest;
using Model = Discord.API.User;
using PresenceModel = Discord.API.Presence;

namespace Discord.WebSocket
{
Expand Down Expand Up @@ -40,9 +41,9 @@ public abstract class SocketUser : SocketEntity<ulong>, IUser
/// <inheritdoc />
public UserStatus Status => Presence.Status;
/// <inheritdoc />
public IImmutableSet<ClientType> ActiveClients => Presence.ActiveClients ?? ImmutableHashSet<ClientType>.Empty;
public IReadOnlyCollection<ClientType> ActiveClients => Presence.ActiveClients ?? ImmutableHashSet<ClientType>.Empty;
/// <inheritdoc />
public IImmutableList<IActivity> Activities => Presence.Activities ?? ImmutableList<IActivity>.Empty;
public IReadOnlyCollection<IActivity> Activities => Presence.Activities ?? ImmutableList<IActivity>.Empty;
/// <summary>
/// Gets mutual guilds shared with this user.
/// </summary>
Expand Down Expand Up @@ -91,6 +92,11 @@ internal virtual bool Update(ClientState state, Model model)
return hasChanges;
}

internal virtual void Update(PresenceModel model)
{
Presence.Update(model);
}

/// <inheritdoc />
public async Task<IDMChannel> CreateDMChannelAsync(RequestOptions options = null)
=> await UserHelper.CreateDMChannelAsync(this, Discord, options).ConfigureAwait(false);
Expand Down

0 comments on commit 9d6dc62

Please sign in to comment.