Concrete class prototype

This commit is contained in:
RogueException
2016-09-22 21:15:37 -03:00
parent ab42129eb9
commit 6319933ed0
394 changed files with 3648 additions and 3224 deletions

View File

@@ -0,0 +1,363 @@
#pragma warning disable CS1591
using Discord.API.Rpc;
using Discord.Net.Queue;
using Discord.Net.Rest;
using Discord.Net.WebSockets;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Discord.API
{
public class DiscordRpcApiClient : DiscordRestApiClient, IDisposable
{
private abstract class RpcRequest
{
public abstract Task SetResultAsync(JToken data, JsonSerializer serializer);
public abstract Task SetExceptionAsync(JToken data, JsonSerializer serializer);
}
private class RpcRequest<T> : RpcRequest
{
public TaskCompletionSource<T> Promise { get; set; }
public RpcRequest(RequestOptions options)
{
Promise = new TaskCompletionSource<T>();
Task.Run(async () =>
{
await Task.Delay(options?.Timeout ?? 15000).ConfigureAwait(false);
Promise.TrySetCanceled(); //Doesn't need to be async, we're already in a separate task
});
}
public override Task SetResultAsync(JToken data, JsonSerializer serializer)
{
return Promise.TrySetResultAsync(data.ToObject<T>(serializer));
}
public override Task SetExceptionAsync(JToken data, JsonSerializer serializer)
{
var error = data.ToObject<ErrorEvent>(serializer);
return Promise.TrySetExceptionAsync(new RpcException(error.Code, error.Message));
}
}
private object _eventLock = new object();
public event Func<string, Task> SentRpcMessage { add { _sentRpcMessageEvent.Add(value); } remove { _sentRpcMessageEvent.Remove(value); } }
private readonly AsyncEvent<Func<string, Task>> _sentRpcMessageEvent = new AsyncEvent<Func<string, Task>>();
public event Func<string, Optional<string>, Optional<object>, Task> ReceivedRpcEvent { add { _receivedRpcEvent.Add(value); } remove { _receivedRpcEvent.Remove(value); } }
private readonly AsyncEvent<Func<string, Optional<string>, Optional<object>, Task>> _receivedRpcEvent = new AsyncEvent<Func<string, Optional<string>, Optional<object>, Task>>();
public event Func<Exception, Task> Disconnected { add { _disconnectedEvent.Add(value); } remove { _disconnectedEvent.Remove(value); } }
private readonly AsyncEvent<Func<Exception, Task>> _disconnectedEvent = new AsyncEvent<Func<Exception, Task>>();
private readonly ConcurrentDictionary<Guid, RpcRequest> _requests;
private readonly RequestQueue _requestQueue;
private readonly IWebSocketClient _webSocketClient;
private readonly SemaphoreSlim _connectionLock;
private readonly string _clientId;
private CancellationTokenSource _stateCancelToken;
private string _origin;
public ConnectionState ConnectionState { get; private set; }
public DiscordRpcApiClient(string clientId, string origin, RestClientProvider restClientProvider, WebSocketProvider webSocketProvider, JsonSerializer serializer = null, RequestQueue requestQueue = null)
: base(restClientProvider, serializer, requestQueue)
{
_connectionLock = new SemaphoreSlim(1, 1);
_clientId = clientId;
_origin = origin;
_requestQueue = requestQueue ?? new RequestQueue();
_requests = new ConcurrentDictionary<Guid, RpcRequest>();
_webSocketClient = webSocketProvider();
//_webSocketClient.SetHeader("user-agent", DiscordConfig.UserAgent); (Causes issues in .Net 4.6+)
_webSocketClient.SetHeader("origin", _origin);
_webSocketClient.BinaryMessage += async (data, index, count) =>
{
using (var compressed = new MemoryStream(data, index + 2, count - 2))
using (var decompressed = new MemoryStream())
{
using (var zlib = new DeflateStream(compressed, CompressionMode.Decompress))
zlib.CopyTo(decompressed);
decompressed.Position = 0;
using (var reader = new StreamReader(decompressed))
using (var jsonReader = new JsonTextReader(reader))
{
var msg = _serializer.Deserialize<API.Rpc.RpcMessage>(jsonReader);
await _receivedRpcEvent.InvokeAsync(msg.Cmd, msg.Event, msg.Data).ConfigureAwait(false);
if (msg.Nonce.IsSpecified && msg.Nonce.Value.HasValue)
ProcessMessage(msg);
}
}
};
_webSocketClient.TextMessage += async text =>
{
using (var reader = new StringReader(text))
using (var jsonReader = new JsonTextReader(reader))
{
var msg = _serializer.Deserialize<API.Rpc.RpcMessage>(jsonReader);
await _receivedRpcEvent.InvokeAsync(msg.Cmd, msg.Event, msg.Data).ConfigureAwait(false);
if (msg.Nonce.IsSpecified && msg.Nonce.Value.HasValue)
ProcessMessage(msg);
}
};
_webSocketClient.Closed += async ex =>
{
await DisconnectAsync().ConfigureAwait(false);
await _disconnectedEvent.InvokeAsync(ex).ConfigureAwait(false);
};
}
internal override void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
_stateCancelToken?.Dispose();
(_webSocketClient as IDisposable)?.Dispose();
}
_isDisposed = true;
}
}
public async Task ConnectAsync()
{
await _connectionLock.WaitAsync().ConfigureAwait(false);
try
{
await ConnectInternalAsync().ConfigureAwait(false);
}
finally { _connectionLock.Release(); }
}
internal override async Task ConnectInternalAsync()
{
/*if (LoginState != LoginState.LoggedIn)
throw new InvalidOperationException("Client is not logged in.");*/
ConnectionState = ConnectionState.Connecting;
try
{
_stateCancelToken = new CancellationTokenSource();
if (_webSocketClient != null)
_webSocketClient.SetCancelToken(_stateCancelToken.Token);
bool success = false;
int port;
string uuid = Guid.NewGuid().ToString();
for ( port = DiscordRpcConfig.PortRangeStart; port <= DiscordRpcConfig.PortRangeEnd; port++)
{
try
{
string url = $"wss://{uuid}.discordapp.io:{port}/?v={DiscordRpcConfig.RpcAPIVersion}&client_id={_clientId}";
await _webSocketClient.ConnectAsync(url).ConfigureAwait(false);
success = true;
break;
}
catch (Exception)
{
}
}
if (!success)
throw new Exception("Unable to connect to the RPC server.");
SetBaseUrl($"https://{uuid}.discordapp.io:{port}/");
ConnectionState = ConnectionState.Connected;
}
catch (Exception)
{
await DisconnectInternalAsync().ConfigureAwait(false);
throw;
}
}
public async Task DisconnectAsync()
{
await _connectionLock.WaitAsync().ConfigureAwait(false);
try
{
await DisconnectInternalAsync().ConfigureAwait(false);
}
finally { _connectionLock.Release(); }
}
internal override async Task DisconnectInternalAsync()
{
if (_webSocketClient == null)
throw new NotSupportedException("This client is not configured with websocket support.");
if (ConnectionState == ConnectionState.Disconnected) return;
ConnectionState = ConnectionState.Disconnecting;
try { _stateCancelToken?.Cancel(false); }
catch { }
await _webSocketClient.DisconnectAsync().ConfigureAwait(false);
ConnectionState = ConnectionState.Disconnected;
}
//Core
public Task<TResponse> SendRpcAsync<TResponse>(string cmd, object payload, GlobalBucket bucket = GlobalBucket.GeneralRpc,
Optional<string> evt = default(Optional<string>), bool ignoreState = false, RequestOptions options = null)
where TResponse : class
=> SendRpcAsyncInternal<TResponse>(cmd, payload, BucketGroup.Global, (int)bucket, 0, evt, ignoreState, options);
public Task<TResponse> SendRpcAsync<TResponse>(string cmd, object payload, GuildBucket bucket, ulong guildId,
Optional<string> evt = default(Optional<string>), bool ignoreState = false, RequestOptions options = null)
where TResponse : class
=> SendRpcAsyncInternal<TResponse>(cmd, payload, BucketGroup.Guild, (int)bucket, guildId, evt, ignoreState, options);
private async Task<TResponse> SendRpcAsyncInternal<TResponse>(string cmd, object payload, BucketGroup group, int bucketId, ulong guildId,
Optional<string> evt, bool ignoreState, RequestOptions options)
where TResponse : class
{
if (!ignoreState)
CheckState();
byte[] bytes = null;
var guid = Guid.NewGuid();
payload = new API.Rpc.RpcMessage { Cmd = cmd, Event = evt, Args = payload, Nonce = guid };
if (payload != null)
{
var json = SerializeJson(payload);
bytes = Encoding.UTF8.GetBytes(json);
}
var requestTracker = new RpcRequest<TResponse>(options);
_requests[guid] = requestTracker;
await _requestQueue.SendAsync(new WebSocketRequest(_webSocketClient, bytes, true, options), group, bucketId, guildId).ConfigureAwait(false);
await _sentRpcMessageEvent.InvokeAsync(cmd).ConfigureAwait(false);
return await requestTracker.Promise.Task.ConfigureAwait(false);
}
//Rpc
public async Task<AuthenticateResponse> SendAuthenticateAsync(RequestOptions options = null)
{
var msg = new AuthenticateParams
{
AccessToken = _authToken
};
return await SendRpcAsync<AuthenticateResponse>("AUTHENTICATE", msg, ignoreState: true, options: options).ConfigureAwait(false);
}
public async Task<AuthorizeResponse> SendAuthorizeAsync(string[] scopes, string rpcToken = null, RequestOptions options = null)
{
var msg = new AuthorizeParams
{
ClientId = _clientId,
Scopes = scopes,
RpcToken = rpcToken != null ? rpcToken : Optional.Create<string>()
};
if (options == null)
options = new RequestOptions();
if (options.Timeout == null)
options.Timeout = 60000; //This requires manual input on the user's end, lets give them more time
return await SendRpcAsync<AuthorizeResponse>("AUTHORIZE", msg, ignoreState: true, options: options).ConfigureAwait(false);
}
public async Task<GetGuildsResponse> SendGetGuildsAsync(RequestOptions options = null)
{
return await SendRpcAsync<GetGuildsResponse>("GET_GUILDS", null, options: options).ConfigureAwait(false);
}
public async Task<RpcGuild> SendGetGuildAsync(ulong guildId, RequestOptions options = null)
{
var msg = new GetGuildParams
{
GuildId = guildId
};
return await SendRpcAsync<RpcGuild>("GET_GUILD", msg, options: options).ConfigureAwait(false);
}
public async Task<GetChannelsResponse> SendGetChannelsAsync(ulong guildId, RequestOptions options = null)
{
var msg = new GetChannelsParams
{
GuildId = guildId
};
return await SendRpcAsync<GetChannelsResponse>("GET_CHANNELS", msg, options: options).ConfigureAwait(false);
}
public async Task<RpcChannel> SendGetChannelAsync(ulong channelId, RequestOptions options = null)
{
var msg = new GetChannelParams
{
ChannelId = channelId
};
return await SendRpcAsync<RpcChannel>("GET_CHANNEL", msg, options: options).ConfigureAwait(false);
}
public async Task<SetLocalVolumeResponse> SendSetLocalVolumeAsync(int volume, RequestOptions options = null)
{
var msg = new SetLocalVolumeParams
{
Volume = volume
};
return await SendRpcAsync<SetLocalVolumeResponse>("SET_LOCAL_VOLUME", msg, options: options).ConfigureAwait(false);
}
public async Task<RpcChannel> SendSelectVoiceChannelAsync(ulong channelId, RequestOptions options = null)
{
var msg = new SelectVoiceChannelParams
{
ChannelId = channelId
};
return await SendRpcAsync<RpcChannel>("SELECT_VOICE_CHANNEL", msg, options: options).ConfigureAwait(false);
}
public async Task<SubscriptionResponse> SendChannelSubscribeAsync(string evt, ulong channelId, RequestOptions options = null)
{
var msg = new ChannelSubscriptionParams
{
ChannelId = channelId
};
return await SendRpcAsync<SubscriptionResponse>("SUBSCRIBE", msg, evt: evt, options: options).ConfigureAwait(false);
}
public async Task<SubscriptionResponse> SendChannelUnsubscribeAsync(string evt, ulong channelId, RequestOptions options = null)
{
var msg = new ChannelSubscriptionParams
{
ChannelId = channelId
};
return await SendRpcAsync<SubscriptionResponse>("UNSUBSCRIBE", msg, evt: evt, options: options).ConfigureAwait(false);
}
public async Task<SubscriptionResponse> SendGuildSubscribeAsync(string evt, ulong guildId, RequestOptions options = null)
{
var msg = new GuildSubscriptionParams
{
GuildId = guildId
};
return await SendRpcAsync<SubscriptionResponse>("SUBSCRIBE", msg, evt: evt, options: options).ConfigureAwait(false);
}
public async Task<SubscriptionResponse> SendGuildUnsubscribeAsync(string evt, ulong guildId, RequestOptions options = null)
{
var msg = new GuildSubscriptionParams
{
GuildId = guildId
};
return await SendRpcAsync<SubscriptionResponse>("UNSUBSCRIBE", msg, evt: evt, options: options).ConfigureAwait(false);
}
private bool ProcessMessage(API.Rpc.RpcMessage msg)
{
RpcRequest requestTracker;
if (_requests.TryGetValue(msg.Nonce.Value.Value, out requestTracker))
{
if (msg.Event.GetValueOrDefault("") == "ERROR")
{
var _ = requestTracker.SetExceptionAsync(msg.Data.GetValueOrDefault() as JToken, _serializer);
}
else
{
var _ = requestTracker.SetResultAsync(msg.Data.GetValueOrDefault() as JToken, _serializer);
}
return true;
}
else
return false;
}
}
}

View File

@@ -0,0 +1,19 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class Application
{
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("icon")]
public string Icon { get; set; }
[JsonProperty("id")]
public ulong Id { get; set; }
[JsonProperty("rpc_origins")]
public string[] RpcOrigins { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class AuthenticateParams
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
}
}

View File

@@ -0,0 +1,18 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
using System;
namespace Discord.API.Rpc
{
public class AuthenticateResponse
{
[JsonProperty("application")]
public Application Application { get; set; }
[JsonProperty("expires")]
public DateTimeOffset Expires { get; set; }
[JsonProperty("user")]
public User User { get; set; }
[JsonProperty("scopes")]
public string[] Scopes { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class AuthorizeParams
{
[JsonProperty("client_id")]
public string ClientId { get; set; }
[JsonProperty("scopes")]
public string[] Scopes { get; set; }
[JsonProperty("rpc_token")]
public Optional<string> RpcToken { get; set; }
}
}

View File

@@ -0,0 +1,12 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
using System;
namespace Discord.API.Rpc
{
public class AuthorizeResponse
{
[JsonProperty("code")]
public string Code { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class ChannelSubscriptionParams
{
[JsonProperty("channel_id")]
public ulong ChannelId { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class ErrorEvent
{
[JsonProperty("code")]
public int Code { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class GetChannelParams
{
[JsonProperty("channel_id")]
public ulong ChannelId { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class GetChannelsParams
{
[JsonProperty("guild_id")]
public ulong GuildId { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class GetChannelsResponse
{
[JsonProperty("channels")]
public RpcChannel[] Channels { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class GetGuildParams
{
[JsonProperty("guild_id")]
public ulong GuildId { get; set; }
}
}

View File

@@ -0,0 +1,7 @@
#pragma warning disable CS1591
namespace Discord.API.Rpc
{
public class GetGuildsParams
{
}
}

View File

@@ -0,0 +1,11 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class GetGuildsResponse
{
[JsonProperty("guilds")]
public RpcUserGuild[] Guilds { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class GuildStatusEvent
{
[JsonProperty("guild")]
public Guild Guild { get; set; }
[JsonProperty("online")]
public int Online { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class GuildSubscriptionParams
{
[JsonProperty("guild_id")]
public ulong GuildId { get; set; }
}
}

View File

@@ -0,0 +1,12 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class MessageEvent
{
[JsonProperty("channel_id")]
public ulong ChannelId { get; set; }
[JsonProperty("message")]
public Message Message { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class ReadyEvent
{
[JsonProperty("v")]
public int Version { get; set; }
[JsonProperty("config")]
public RpcConfig Config { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class RpcChannel : Channel
{
[JsonProperty("voice_states")]
public VoiceState[] VoiceStates { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class RpcConfig
{
[JsonProperty("cdn_host")]
public string CdnHost { get; set; }
[JsonProperty("api_endpoint")]
public string ApiEndpoint { get; set; }
[JsonProperty("environment")]
public string Environment { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class RpcGuild : Guild
{
[JsonProperty("online")]
public int Online { get; set; }
[JsonProperty("members")]
public GuildMember[] Members { get; set; }
}
}

View File

@@ -0,0 +1,20 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
using System;
namespace Discord.API.Rpc
{
public class RpcMessage
{
[JsonProperty("cmd")]
public string Cmd { get; set; }
[JsonProperty("nonce")]
public Optional<Guid?> Nonce { get; set; }
[JsonProperty("evt")]
public Optional<string> Event { get; set; }
[JsonProperty("data")]
public Optional<object> Data { get; set; }
[JsonProperty("args")]
public object Args { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class RpcUserGuild
{
[JsonProperty("id")]
public ulong Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class SelectVoiceChannelParams
{
[JsonProperty("channel_id")]
public ulong? ChannelId { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class SetLocalVolumeParams
{
[JsonProperty("volume")]
public int Volume { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class SetLocalVolumeResponse
{
[JsonProperty("user_id")]
public ulong UserId { get; set; }
[JsonProperty("volume")]
public int Volume { get; set; }
}
}

View File

@@ -0,0 +1,7 @@
#pragma warning disable CS1591
namespace Discord.API.Rpc
{
public class SpeakingEvent
{
}
}

View File

@@ -0,0 +1,11 @@
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rpc
{
public class SubscriptionResponse
{
[JsonProperty("evt")]
public string Event { get; set; }
}
}

View File

@@ -0,0 +1,7 @@
#pragma warning disable CS1591
namespace Discord.API.Rpc
{
public class VoiceStateEvent
{
}
}

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>5688a353-121e-40a1-8bfa-b17b91fb48fb</ProjectGuid>
<RootNamespace>Discord.Net.Rpc</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>

View File

@@ -0,0 +1,64 @@
using System;
using System.Threading.Tasks;
namespace Discord.Rpc
{
public partial class DiscordRpcClient
{
//General
public event Func<Task> Connected
{
add { _connectedEvent.Add(value); }
remove { _connectedEvent.Remove(value); }
}
private readonly AsyncEvent<Func<Task>> _connectedEvent = new AsyncEvent<Func<Task>>();
public event Func<Exception, Task> Disconnected
{
add { _disconnectedEvent.Add(value); }
remove { _disconnectedEvent.Remove(value); }
}
private readonly AsyncEvent<Func<Exception, Task>> _disconnectedEvent = new AsyncEvent<Func<Exception, Task>>();
public event Func<Task> Ready
{
add { _readyEvent.Add(value); }
remove { _readyEvent.Remove(value); }
}
private readonly AsyncEvent<Func<Task>> _readyEvent = new AsyncEvent<Func<Task>>();
//Guild
public event Func<Task> GuildUpdated
{
add { _guildUpdatedEvent.Add(value); }
remove { _guildUpdatedEvent.Remove(value); }
}
private readonly AsyncEvent<Func<Task>> _guildUpdatedEvent = new AsyncEvent<Func<Task>>();
//Voice
public event Func<Task> VoiceStateUpdated
{
add { _voiceStateUpdatedEvent.Add(value); }
remove { _voiceStateUpdatedEvent.Remove(value); }
}
private readonly AsyncEvent<Func<Task>> _voiceStateUpdatedEvent = new AsyncEvent<Func<Task>>();
//Messages
public event Func<ulong, IMessage, Task> MessageReceived
{
add { _messageReceivedEvent.Add(value); }
remove { _messageReceivedEvent.Remove(value); }
}
private readonly AsyncEvent<Func<ulong, IMessage, Task>> _messageReceivedEvent = new AsyncEvent<Func<ulong, IMessage, Task>>();
public event Func<ulong, IMessage, Task> MessageUpdated
{
add { _messageUpdatedEvent.Add(value); }
remove { _messageUpdatedEvent.Remove(value); }
}
private readonly AsyncEvent<Func<ulong, IMessage, Task>> _messageUpdatedEvent = new AsyncEvent<Func<ulong, IMessage, Task>>();
public event Func<ulong, ulong, Task> MessageDeleted
{
add { _messageDeletedEvent.Add(value); }
remove { _messageDeletedEvent.Remove(value); }
}
private readonly AsyncEvent<Func<ulong, ulong, Task>> _messageDeletedEvent = new AsyncEvent<Func<ulong, ulong, Task>>();
}
}

View File

@@ -0,0 +1,418 @@
using Discord.API.Rpc;
using Discord.Logging;
using Discord.Net.Converters;
using Discord.Net.Queue;
using Discord.Rest;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Discord.Rpc
{
public partial class DiscordRpcClient : DiscordRestClient
{
private readonly ILogger _rpcLogger;
private readonly JsonSerializer _serializer;
private TaskCompletionSource<bool> _connectTask;
private CancellationTokenSource _cancelToken, _reconnectCancelToken;
private Task _reconnectTask;
private bool _canReconnect;
public ConnectionState ConnectionState { get; private set; }
//From DiscordRpcConfig
internal int ConnectionTimeout { get; private set; }
public new API.DiscordRpcApiClient ApiClient => base.ApiClient as API.DiscordRpcApiClient;
/// <summary> Creates a new RPC discord client. </summary>
public DiscordRpcClient(string clientId, string origin) : this(new DiscordRpcConfig(clientId, origin)) { }
/// <summary> Creates a new RPC discord client. </summary>
public DiscordRpcClient(DiscordRpcConfig config)
: base(config, CreateApiClient(config))
{
ConnectionTimeout = config.ConnectionTimeout;
_rpcLogger = LogManager.CreateLogger("RPC");
_serializer = new JsonSerializer { ContractResolver = new DiscordContractResolver() };
_serializer.Error += (s, e) =>
{
_rpcLogger.WarningAsync(e.ErrorContext.Error).GetAwaiter().GetResult();
e.ErrorContext.Handled = true;
};
ApiClient.SentRpcMessage += async opCode => await _rpcLogger.DebugAsync($"Sent {opCode}").ConfigureAwait(false);
ApiClient.ReceivedRpcEvent += ProcessMessageAsync;
ApiClient.Disconnected += async ex =>
{
if (ex != null)
{
await _rpcLogger.WarningAsync($"Connection Closed", ex).ConfigureAwait(false);
await StartReconnectAsync(ex).ConfigureAwait(false);
}
else
await _rpcLogger.WarningAsync($"Connection Closed").ConfigureAwait(false);
};
}
private static API.DiscordRpcApiClient CreateApiClient(DiscordRpcConfig config)
=> new API.DiscordRpcApiClient(config.ClientId, config.Origin, config.RestClientProvider, config.WebSocketProvider, requestQueue: new RequestQueue());
internal override void Dispose(bool disposing)
{
if (!_isDisposed)
ApiClient.Dispose();
}
protected override Task ValidateTokenAsync(TokenType tokenType, string token)
{
return Task.CompletedTask; //Validation is done in DiscordRpcAPIClient
}
/// <inheritdoc />
public Task ConnectAsync() => ConnectAsync(false);
internal async Task ConnectAsync(bool ignoreLoginCheck)
{
await _connectionLock.WaitAsync().ConfigureAwait(false);
try
{
await ConnectInternalAsync(ignoreLoginCheck, false).ConfigureAwait(false);
}
finally { _connectionLock.Release(); }
}
private async Task ConnectInternalAsync(bool ignoreLoginCheck, bool isReconnecting)
{
if (!ignoreLoginCheck && LoginState != LoginState.LoggedIn)
throw new InvalidOperationException("You must log in before connecting.");
if (!isReconnecting && _reconnectCancelToken != null && !_reconnectCancelToken.IsCancellationRequested)
_reconnectCancelToken.Cancel();
var state = ConnectionState;
if (state == ConnectionState.Connecting || state == ConnectionState.Connected)
await DisconnectInternalAsync(null, isReconnecting).ConfigureAwait(false);
ConnectionState = ConnectionState.Connecting;
await _rpcLogger.InfoAsync("Connecting").ConfigureAwait(false);
try
{
var connectTask = new TaskCompletionSource<bool>();
_connectTask = connectTask;
_cancelToken = new CancellationTokenSource();
//Abort connection on timeout
var _ = Task.Run(async () =>
{
await Task.Delay(ConnectionTimeout);
connectTask.TrySetException(new TimeoutException());
});
await ApiClient.ConnectAsync().ConfigureAwait(false);
await _connectedEvent.InvokeAsync().ConfigureAwait(false);
await _connectTask.Task.ConfigureAwait(false);
if (!isReconnecting)
_canReconnect = true;
ConnectionState = ConnectionState.Connected;
await _rpcLogger.InfoAsync("Connected").ConfigureAwait(false);
}
catch (Exception)
{
await DisconnectInternalAsync(null, isReconnecting).ConfigureAwait(false);
throw;
}
}
/// <inheritdoc />
public async Task DisconnectAsync()
{
if (_connectTask?.TrySetCanceled() ?? false) return;
await _connectionLock.WaitAsync().ConfigureAwait(false);
try
{
await DisconnectInternalAsync(null, false).ConfigureAwait(false);
}
finally { _connectionLock.Release(); }
}
private async Task DisconnectInternalAsync(Exception ex, bool isReconnecting)
{
if (!isReconnecting)
{
_canReconnect = false;
if (_reconnectCancelToken != null && !_reconnectCancelToken.IsCancellationRequested)
_reconnectCancelToken.Cancel();
}
if (ConnectionState == ConnectionState.Disconnected) return;
ConnectionState = ConnectionState.Disconnecting;
await _rpcLogger.InfoAsync("Disconnecting").ConfigureAwait(false);
await _rpcLogger.DebugAsync("Disconnecting - CancelToken").ConfigureAwait(false);
//Signal tasks to complete
try { _cancelToken.Cancel(); } catch { }
await _rpcLogger.DebugAsync("Disconnecting - ApiClient").ConfigureAwait(false);
//Disconnect from server
await ApiClient.DisconnectAsync().ConfigureAwait(false);
ConnectionState = ConnectionState.Disconnected;
await _rpcLogger.InfoAsync("Disconnected").ConfigureAwait(false);
await _disconnectedEvent.InvokeAsync(ex).ConfigureAwait(false);
}
private async Task StartReconnectAsync(Exception ex)
{
await _connectionLock.WaitAsync().ConfigureAwait(false);
try
{
if (!_canReconnect || _reconnectTask != null) return;
_reconnectCancelToken = new CancellationTokenSource();
_reconnectTask = ReconnectInternalAsync(ex, _reconnectCancelToken.Token);
}
finally { _connectionLock.Release(); }
}
private async Task ReconnectInternalAsync(Exception ex, CancellationToken cancelToken)
{
if (ex == null)
{
if (_connectTask?.TrySetCanceled() ?? false) return;
}
else
{
if (_connectTask?.TrySetException(ex) ?? false) return;
}
try
{
Random jitter = new Random();
int nextReconnectDelay = 1000;
while (true)
{
await Task.Delay(nextReconnectDelay, cancelToken).ConfigureAwait(false);
nextReconnectDelay = nextReconnectDelay * 2 + jitter.Next(-250, 250);
if (nextReconnectDelay > 60000)
nextReconnectDelay = 60000;
await _connectionLock.WaitAsync().ConfigureAwait(false);
try
{
if (cancelToken.IsCancellationRequested) return;
await ConnectInternalAsync(false, true).ConfigureAwait(false);
_reconnectTask = null;
return;
}
catch (Exception ex2)
{
await _rpcLogger.WarningAsync("Reconnect failed", ex2).ConfigureAwait(false);
}
finally { _connectionLock.Release(); }
}
}
catch (OperationCanceledException)
{
await _connectionLock.WaitAsync().ConfigureAwait(false);
try
{
await _rpcLogger.DebugAsync("Reconnect cancelled").ConfigureAwait(false);
_reconnectTask = null;
}
finally { _connectionLock.Release(); }
}
}
public async Task<string> AuthorizeAsync(string[] scopes, string rpcToken = null)
{
await ConnectAsync(true).ConfigureAwait(false);
var result = await ApiClient.SendAuthorizeAsync(scopes, rpcToken).ConfigureAwait(false);
await DisconnectAsync().ConfigureAwait(false);
return result.Code;
}
public async Task SubscribeGuild(ulong guildId, params RpcChannelEvent[] events)
{
Preconditions.AtLeast(events?.Length ?? 0, 1, nameof(events));
for (int i = 0; i < events.Length; i++)
await ApiClient.SendGuildSubscribeAsync(GetEventName(events[i]), guildId);
}
public async Task UnsubscribeGuild(ulong guildId, params RpcChannelEvent[] events)
{
Preconditions.AtLeast(events?.Length ?? 0, 1, nameof(events));
for (int i = 0; i < events.Length; i++)
await ApiClient.SendGuildUnsubscribeAsync(GetEventName(events[i]), guildId);
}
public async Task SubscribeChannel(ulong channelId, params RpcChannelEvent[] events)
{
Preconditions.AtLeast(events?.Length ?? 0, 1, nameof(events));
for (int i = 0; i < events.Length; i++)
await ApiClient.SendChannelSubscribeAsync(GetEventName(events[i]), channelId);
}
public async Task UnsubscribeChannel(ulong channelId, params RpcChannelEvent[] events)
{
Preconditions.AtLeast(events?.Length ?? 0, 1, nameof(events));
for (int i = 0; i < events.Length; i++)
await ApiClient.SendChannelUnsubscribeAsync(GetEventName(events[i]), channelId);
}
private static string GetEventName(RpcGuildEvent rpcEvent)
{
switch (rpcEvent)
{
case RpcGuildEvent.GuildStatus: return "GUILD_STATUS";
default:
throw new InvalidOperationException($"Unknown RPC Guild Event: {rpcEvent}");
}
}
private static string GetEventName(RpcChannelEvent rpcEvent)
{
switch (rpcEvent)
{
case RpcChannelEvent.VoiceStateCreate: return "VOICE_STATE_CREATE";
case RpcChannelEvent.VoiceStateUpdate: return "VOICE_STATE_UPDATE";
case RpcChannelEvent.VoiceStateDelete: return "VOICE_STATE_DELETE";
case RpcChannelEvent.SpeakingStart: return "SPEAKING_START";
case RpcChannelEvent.SpeakingStop: return "SPEAKING_STOP";
case RpcChannelEvent.MessageCreate: return "MESSAGE_CREATE";
case RpcChannelEvent.MessageUpdate: return "MESSAGE_UPDATE";
case RpcChannelEvent.MessageDelete: return "MESSAGE_DELETE";
default:
throw new InvalidOperationException($"Unknown RPC Channel Event: {rpcEvent}");
}
}
private async Task ProcessMessageAsync(string cmd, Optional<string> evnt, Optional<object> payload)
{
try
{
switch (cmd)
{
case "DISPATCH":
switch (evnt.Value)
{
//Connection
case "READY":
{
await _rpcLogger.DebugAsync("Received Dispatch (READY)").ConfigureAwait(false);
var data = (payload.Value as JToken).ToObject<ReadyEvent>(_serializer);
var cancelToken = _cancelToken;
var _ = Task.Run(async () =>
{
try
{
RequestOptions options = new RequestOptions
{
//CancellationToken = cancelToken //TODO: Implement
};
if (LoginState != LoginState.LoggedOut)
await ApiClient.SendAuthenticateAsync(options).ConfigureAwait(false); //Has bearer
var __ = _connectTask.TrySetResultAsync(true); //Signal the .Connect() call to complete
await _rpcLogger.InfoAsync("Ready").ConfigureAwait(false);
}
catch (Exception ex)
{
await _rpcLogger.ErrorAsync($"Error handling {cmd}{(evnt.IsSpecified ? $" ({evnt})" : "")}", ex).ConfigureAwait(false);
return;
}
});
}
break;
//Guilds
case "GUILD_STATUS":
{
await _rpcLogger.DebugAsync("Received Dispatch (GUILD_STATUS)").ConfigureAwait(false);
await _guildUpdatedEvent.InvokeAsync().ConfigureAwait(false);
}
break;
//Voice
case "VOICE_STATE_CREATE":
{
await _rpcLogger.DebugAsync("Received Dispatch (VOICE_STATE_CREATE)").ConfigureAwait(false);
await _voiceStateUpdatedEvent.InvokeAsync().ConfigureAwait(false);
}
break;
case "VOICE_STATE_UPDATE":
{
await _rpcLogger.DebugAsync("Received Dispatch (VOICE_STATE_UPDATE)").ConfigureAwait(false);
await _voiceStateUpdatedEvent.InvokeAsync().ConfigureAwait(false);
}
break;
case "VOICE_STATE_DELETE":
{
await _rpcLogger.DebugAsync("Received Dispatch (VOICE_STATE_DELETE)").ConfigureAwait(false);
await _voiceStateUpdatedEvent.InvokeAsync().ConfigureAwait(false);
}
break;
case "SPEAKING_START":
{
await _rpcLogger.DebugAsync("Received Dispatch (SPEAKING_START)").ConfigureAwait(false);
await _voiceStateUpdatedEvent.InvokeAsync().ConfigureAwait(false);
}
break;
case "SPEAKING_STOP":
{
await _rpcLogger.DebugAsync("Received Dispatch (SPEAKING_STOP)").ConfigureAwait(false);
await _voiceStateUpdatedEvent.InvokeAsync().ConfigureAwait(false);
}
break;
//Messages
case "MESSAGE_CREATE":
{
await _rpcLogger.DebugAsync("Received Dispatch (MESSAGE_CREATE)").ConfigureAwait(false);
var data = (payload.Value as JToken).ToObject<MessageEvent>(_serializer);
var msg = new RpcMessage(this, data.Message);
await _messageReceivedEvent.InvokeAsync(data.ChannelId, msg).ConfigureAwait(false);
}
break;
case "MESSAGE_UPDATE":
{
await _rpcLogger.DebugAsync("Received Dispatch (MESSAGE_UPDATE)").ConfigureAwait(false);
var data = (payload.Value as JToken).ToObject<MessageEvent>(_serializer);
var msg = new RpcMessage(this, data.Message);
await _messageUpdatedEvent.InvokeAsync(data.ChannelId, msg).ConfigureAwait(false);
}
break;
case "MESSAGE_DELETE":
{
await _rpcLogger.DebugAsync("Received Dispatch (MESSAGE_DELETE)").ConfigureAwait(false);
var data = (payload.Value as JToken).ToObject<MessageEvent>(_serializer);
await _messageDeletedEvent.InvokeAsync(data.ChannelId, data.Message.Id).ConfigureAwait(false);
}
break;
//Others
default:
await _rpcLogger.WarningAsync($"Unknown Dispatch ({evnt})").ConfigureAwait(false);
return;
}
break;
/*default: //Other opcodes are used for command responses
await _rpcLogger.WarningAsync($"Unknown OpCode ({cmd})").ConfigureAwait(false);
return;*/
}
}
catch (Exception ex)
{
await _rpcLogger.ErrorAsync($"Error handling {cmd}{(evnt.IsSpecified ? $" ({evnt})" : "")}", ex).ConfigureAwait(false);
return;
}
}
}
}

View File

@@ -0,0 +1,30 @@
using Discord.Net.WebSockets;
using Discord.Rest;
namespace Discord.Rpc
{
public class DiscordRpcConfig : DiscordRestConfig
{
public const int RpcAPIVersion = 1;
public const int PortRangeStart = 6463;
public const int PortRangeEnd = 6472;
public DiscordRpcConfig(string clientId, string origin)
{
ClientId = clientId;
Origin = origin;
}
/// <summary> Gets or sets the Discord client/application id used for this RPC connection. </summary>
public string ClientId { get; }
/// <summary> Gets or sets the origin used for this RPC connection. </summary>
public string Origin { get; }
/// <summary> Gets or sets the time, in milliseconds, to wait for a connection to complete before aborting. </summary>
public int ConnectionTimeout { get; set; } = 30000;
/// <summary> Gets or sets the provider used to generate new websocket connections. </summary>
public WebSocketProvider WebSocketProvider { get; set; } = () => new DefaultWebSocketClient();
}
}

View File

@@ -0,0 +1,8 @@
namespace Discord.Rpc
{
/*public interface IRemoteUserGuild : ISnowflakeEntity
{
/// <summary> Gets the name of this guild. </summary>
string Name { get; }
}*/
}

View File

@@ -0,0 +1,28 @@
using Discord.Rest;
using System;
using Model = Discord.API.Rpc.RpcUserGuild;
namespace Discord.Rpc
{
/*internal class RemoteUserGuild : IRemoteUserGuild, ISnowflakeEntity
{
public ulong Id { get; }
public DiscordRestClient Discord { get; }
public string Name { get; private set; }
public DateTimeOffset CreatedAt => DateTimeUtils.FromSnowflake(Id);
public RemoteUserGuild(DiscordRestClient discord, Model model)
{
Id = model.Id;
Discord = discord;
Update(model);
}
public void Update(Model model)
{
Name = model.Name;
}
bool IEntity<ulong>.IsAttached => false;
}*/
}

View File

@@ -0,0 +1,15 @@
using Discord.Rest;
namespace Discord.Rpc
{
internal class RpcMessage : Message
{
public override DiscordRestClient Discord { get; }
public RpcMessage(DiscordRpcClient discord, API.Message model)
: base(null, model.Author.IsSpecified ? new User(model.Author.Value) : null, model)
{
Discord = discord;
}
}
}

View File

@@ -0,0 +1,19 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Discord.Net.Rpc")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5688a353-121e-40a1-8bfa-b17b91fb48fb")]

View File

@@ -0,0 +1,14 @@
namespace Discord.Rpc
{
public enum RpcChannelEvent
{
VoiceStateCreate,
VoiceStateUpdate,
VoiceStateDelete,
SpeakingStart,
SpeakingStop,
MessageCreate,
MessageUpdate,
MessageDelete
}
}

View File

@@ -0,0 +1,7 @@
namespace Discord.Rpc
{
public enum RpcGuildEvent
{
GuildStatus
}
}

View File

@@ -0,0 +1,20 @@
{
"version": "1.0.0-*",
"buildOptions": {
"compile": {
"include": [ "../Discord.Net.Entities/**.cs", "../Discord.Net.Utils/**.cs" ]
},
"define": [ "RPC" ]
},
"dependencies": {
"NETStandard.Library": "1.6.0"
},
"frameworks": {
"netstandard1.6": {
"imports": "dnxcore50"
}
}
}