using System.Text.Json; using System.Text.Json.Serialization; using DysonNetwork.Shared.Proto; using NodaTime; using NodaTime.Serialization.SystemTextJson; namespace DysonNetwork.Shared.Data; public class WebSocketPacket { public string Type { get; set; } = null!; [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public object? Data { get; set; } = null!; [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? Endpoint { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? ErrorMessage { get; set; } /// /// Creates a WebSocketPacket from raw WebSocket message bytes /// /// Raw WebSocket message bytes /// Deserialized WebSocketPacket public static WebSocketPacket FromBytes(byte[] bytes) { var json = System.Text.Encoding.UTF8.GetString(bytes); return JsonSerializer.Deserialize(json, GrpcTypeHelper.SerializerOptions) ?? throw new JsonException("Failed to deserialize WebSocketPacket"); } /// /// Deserializes the Data property to the specified type T /// /// Target type to deserialize to /// Deserialized data of type T public T? GetData() { if (Data is T typedData) return typedData; return JsonSerializer.Deserialize( JsonSerializer.Serialize(Data, GrpcTypeHelper.SerializerOptions), GrpcTypeHelper.SerializerOptions ); } /// /// Serializes this WebSocketPacket to a byte array for sending over WebSocket /// /// Byte array representation of the packet public byte[] ToBytes() { var json = JsonSerializer.Serialize(this, GrpcTypeHelper.SerializerOptions); return System.Text.Encoding.UTF8.GetBytes(json); } public Shared.Proto.WebSocketPacket ToProtoValue() { return new Shared.Proto.WebSocketPacket { Type = Type, Data = GrpcTypeHelper.ConvertObjectToByteString(Data), ErrorMessage = ErrorMessage }; } public static WebSocketPacket FromProtoValue(Shared.Proto.WebSocketPacket packet) { return new WebSocketPacket { Type = packet.Type, Data = GrpcTypeHelper.ConvertByteStringToObject(packet.Data), ErrorMessage = packet.ErrorMessage }; } }