Archived
1
0
Fork 0
This repository has been archived on 2024-05-21. You can view files and clone it, but cannot push or open issues or pull requests.
maki/Maki/Gateway/GatewayShard.cs

226 lines
7.2 KiB
C#
Raw Normal View History

2017-11-13 11:39:27 +00:00
using Maki.Structures.Gateway;
2017-05-14 12:02:51 +00:00
using Newtonsoft.Json;
using System;
using WebSocketSharp;
namespace Maki.Gateway
{
/// <summary>
/// Gateway connection shard
/// </summary>
class GatewayShard : IDisposable
{
private const string GATEWAY_URL = "{0}?v={1}&encoding=json";
private readonly string GatewayUrl;
2017-05-14 12:02:51 +00:00
/// <summary>
/// Session key for continuing a resuming after disconnecting
/// </summary>
2017-11-13 11:39:27 +00:00
private string Session;
2017-05-14 12:02:51 +00:00
/// <summary>
/// Websocket container
/// </summary>
2017-11-13 10:38:12 +00:00
private WebSocket WebSocket;
2017-05-14 12:02:51 +00:00
/// <summary>
/// Interval at which heartbeats are sent
/// </summary>
public TimeSpan HeartbeatInterval { get; private set; }
/// <summary>
/// Last sequence received from the gateway, primarily used for resuming connections and getting the data that was missed
/// </summary>
public int? LastSequence { get; private set; } = null;
/// <summary>
/// Identifier for this Shard
/// </summary>
public readonly int Id;
/// <summary>
/// Parent DiscordClient instance
/// </summary>
2017-11-13 11:39:27 +00:00
private readonly Discord Client;
2017-05-14 12:02:51 +00:00
/// <summary>
/// Heartbeat handler
/// </summary>
2017-11-13 11:39:27 +00:00
private readonly GatewayHeartbeatManager HeartbeatHandler;
/// <summary>
/// Fires when a payload is received.
/// </summary>
public event Action<GatewayShard, GatewayPayload> OnSocketPayload;
2017-05-14 12:02:51 +00:00
/// <summary>
/// Constructor
/// </summary>
/// <param name="id">Shard Id</param>
/// <param name="client">Parent DiscordClient instance</param>
/// <param name="connect">Whether to immediately call Connect()</param>
public GatewayShard(int id, Discord client, bool connect = true)
2017-05-14 12:02:51 +00:00
{
Id = id;
Client = client;
2017-11-13 11:39:27 +00:00
HeartbeatHandler = new GatewayHeartbeatManager(this);
GatewayUrl = string.Format(GATEWAY_URL, Client.Gateway, Discord.GATEWAY_VERSION);
if (connect)
Connect();
2017-05-14 12:02:51 +00:00
}
2017-11-13 11:39:27 +00:00
2017-05-14 12:02:51 +00:00
/// <summary>
2017-11-13 11:39:27 +00:00
/// Event handler for WebSocketSharp's OnClose event, stops heartbeats and reconnects if the close wasn't clean
2017-05-14 12:02:51 +00:00
/// </summary>
/// <param name="sender">Sender object</param>
/// <param name="e">Event arguments</param>
private void WebSocket_OnClose(object sender, CloseEventArgs e)
{
2017-11-13 11:39:27 +00:00
HeartbeatHandler.Stop();
2017-05-14 12:02:51 +00:00
2017-08-09 21:23:43 +00:00
if (!e.WasClean || e.Code != 1000)
2017-05-14 12:02:51 +00:00
Connect();
}
/// <summary>
/// Event handler for WebSocketSharp's OnOpen event, handles gateway instructions and forwards to our events
/// </summary>
/// <param name="sender">Sender object</param>
/// <param name="e">Event arguments</param>
private void WebSocket_OnMessage(object sender, MessageEventArgs e)
{
// ignore non-text messages
if (!e.IsText)
return;
2017-11-13 11:39:27 +00:00
Console.WriteLine(e.Data.Replace(Client.Token, new string('*', Client.Token.Length)));
2017-05-14 12:02:51 +00:00
GatewayPayload payload = JsonConvert.DeserializeObject<GatewayPayload>(e.Data);
2017-11-13 11:39:27 +00:00
OnSocketPayload?.Invoke(this, payload);
2017-05-14 12:02:51 +00:00
switch (payload.OPCode) {
case GatewayOPCode.Dispatch:
LastSequence = payload.Sequence;
2017-11-13 11:39:27 +00:00
if (payload.Name == "READY")
{
GatewayReady ready = payload.DataAs<GatewayReady>();
Session = ready.Session;
2017-05-14 12:02:51 +00:00
}
break;
case GatewayOPCode.Hello:
GatewayHello hello = payload.DataAs<GatewayHello>();
HeartbeatInterval = TimeSpan.FromMilliseconds(hello.HeartbeatInterval);
2017-11-13 11:39:27 +00:00
HeartbeatHandler.Start();
2017-05-14 12:02:51 +00:00
2017-11-13 11:39:27 +00:00
if (string.IsNullOrEmpty(Session))
Send(GatewayOPCode.Identify, new GatewayIdentification
{
Token = Client.Token,
2017-05-14 12:02:51 +00:00
Compress = false,
LargeThreshold = 250,
2017-11-13 11:39:27 +00:00
Shard = new int[] { Id, Client.ShardClient.ShardCount },
Properties = new GatewayIdentificationProperties
{
2017-11-13 10:38:12 +00:00
OperatingSystem = "windows",
Browser = "Maki",
Device = "Maki",
2017-05-14 12:02:51 +00:00
Referrer = string.Empty,
ReferringDomain = string.Empty,
}
});
else
2017-11-13 11:39:27 +00:00
Send(GatewayOPCode.Resume, new GatewayResume
{
2017-05-14 12:02:51 +00:00
LastSequence = LastSequence ?? default(int),
2017-11-13 11:39:27 +00:00
Token = Client.Token,
Session = Session,
2017-05-14 12:02:51 +00:00
});
break;
}
}
#region IDisposable
private bool IsDisposed = false;
private void Dispose(bool disposing)
{
if (IsDisposed)
return;
IsDisposed = true;
Disconnect();
if (disposing)
GC.SuppressFinalize(this);
2017-05-14 12:02:51 +00:00
}
~GatewayShard()
=> Dispose(false);
2017-05-14 12:02:51 +00:00
public void Dispose()
=> Dispose(true);
2017-05-14 12:02:51 +00:00
#endregion
/// <summary>
/// Connects to the gateway
/// </summary>
public void Connect()
{
WebSocket = new WebSocket(GatewayUrl);
2017-05-14 12:02:51 +00:00
// make wss not log anything on its own
2017-11-13 10:38:12 +00:00
WebSocket.Log.Output = (LogData logData, string path) => { };
2017-05-14 12:02:51 +00:00
2017-11-13 10:38:12 +00:00
WebSocket.OnClose += WebSocket_OnClose;
WebSocket.OnMessage += WebSocket_OnMessage;
2017-05-14 12:02:51 +00:00
2017-11-13 10:38:12 +00:00
WebSocket.Connect();
2017-05-14 12:02:51 +00:00
}
/// <summary>
/// Stops heartbeats and closes gateway connection for this shard
/// </summary>
public void Disconnect()
{
2017-11-13 11:39:27 +00:00
HeartbeatHandler.Stop();
2017-05-14 12:02:51 +00:00
2017-11-13 10:38:12 +00:00
if (WebSocket.ReadyState != WebSocketState.Closed)
WebSocket?.Close(CloseStatusCode.Normal);
2017-05-14 12:02:51 +00:00
}
/// <summary>
/// Serialises and sends a json object
/// </summary>
/// <typeparam name="T">Type to serialise as</typeparam>
/// <param name="data">Data to serialise and send</param>
public void Send<T>(T data)
{
2017-11-13 10:38:12 +00:00
string json = JsonConvert.SerializeObject(data, typeof(T), new JsonSerializerSettings());
2017-11-13 11:39:27 +00:00
Console.WriteLine(json.Replace(Client.Token, new string('*', Client.Token.Length)));
2017-11-13 10:38:12 +00:00
WebSocket.Send(json);
2017-05-14 12:02:51 +00:00
}
/// <summary>
/// Serialises and sends a Gateway Payload
/// </summary>
/// <param name="opcode">Opcode to use</param>
/// <param name="data">Data to send</param>
public void Send(GatewayOPCode opcode, object data)
2017-11-13 11:39:27 +00:00
=> Send(new GatewayPayload
2017-05-14 12:02:51 +00:00
{
OPCode = opcode,
Data = data
});
}
}