71 lines
2.4 KiB
C#
71 lines
2.4 KiB
C#
using Newtonsoft.Json.Linq;
|
|
|
|
using System.Diagnostics.CodeAnalysis;
|
|
|
|
namespace bts.websocket_core {
|
|
|
|
//Holds request id, request type, and request parameters
|
|
public class WebsocketRequest {
|
|
public enum REQUEST_TYPES {
|
|
SUBSCRIBE = 1,
|
|
UNSUBSCRIBE_ALL,
|
|
UNSUBSCRIBE,
|
|
ENTER_ORDER,
|
|
DELETE_ORDER,
|
|
DELETE,
|
|
PATCH,
|
|
UNKOWN = 0
|
|
|
|
}
|
|
public readonly WebsocketRequestID id;
|
|
public readonly WebsocketClientID client_id;
|
|
public readonly JObject parameters;
|
|
public readonly REQUEST_TYPES type;
|
|
|
|
private static bool TryParseJson(string json, [NotNullWhen(true)] out ulong? _message_id, out REQUEST_TYPES type, [NotNullWhen(true)] out JObject? para, [NotNullWhen(false)] out string message) {
|
|
para = null;
|
|
type = REQUEST_TYPES.UNKOWN;
|
|
JObject request;
|
|
_message_id = null;
|
|
try {
|
|
request = JObject.Parse(json);
|
|
} catch (Newtonsoft.Json.JsonReaderException ex) {
|
|
message = $"Incorrect Json: {ex.Path}";
|
|
return false;
|
|
}
|
|
if (!WebsocketJsonParsers.TryParse<ulong>(request, "id", out _message_id, out message) || _message_id == null) {
|
|
return false;
|
|
}
|
|
REQUEST_TYPES? rt;
|
|
if (!WebsocketJsonParsers.TryParse<REQUEST_TYPES>(request, "method", out rt, out message)) {
|
|
return false;
|
|
}
|
|
type = rt ?? REQUEST_TYPES.UNKOWN;
|
|
para = (JObject?)request["params"] ?? new JObject();
|
|
return true;
|
|
}
|
|
public static bool TryGetWebSocketRequest(WebsocketClientID cid, string json, [NotNullWhen(true)] out WebsocketRequest? wr, out string message) {
|
|
JObject? jobj;
|
|
REQUEST_TYPES rt;
|
|
if (TryParseJson(json, out ulong? _message_id, out rt, out jobj, out message)) {
|
|
wr = new WebsocketRequest(cid, new WebsocketRequestID((ulong)_message_id), jobj, rt);
|
|
return true;
|
|
}
|
|
wr = null;
|
|
return false;
|
|
}
|
|
private WebsocketRequest(
|
|
WebsocketClientID _cid,
|
|
WebsocketRequestID _id,
|
|
JObject jobj,
|
|
REQUEST_TYPES rt
|
|
) {
|
|
(client_id, id, parameters, type) = (_cid, _id, jobj, rt);
|
|
}
|
|
public WebsocketRequest(WebsocketRequest other, JObject para) {
|
|
client_id = other.client_id;
|
|
id = other.id;
|
|
(parameters, type) = (para, other.type);
|
|
}
|
|
}
|
|
} |