/* This software is licensed by the MIT License, see LICENSE file */ /* Copyright © 2024-2025 Gregory Lirent */ using Google.Protobuf; using System.Reflection; using WinIPC.Models; namespace WinIPC.Utils { public static class PayloadHandler { public static byte[] Serialize(T message) where T : IMessage { if (message == null) { throw new ArgumentNullException(nameof(message), "Protobuf message cannot be null for serialization."); } return message.ToByteArray(); } public static T Deserialize(byte[] data) where T : IMessage, new() { if (data == null) { throw new ArgumentNullException(nameof(data), "Byte array cannot be null for deserialization."); } PropertyInfo? parserProperty = typeof(T).GetProperty("Parser", BindingFlags.Static | BindingFlags.Public); if (parserProperty == null) { throw new InvalidOperationException($"Type {typeof(T).Name} does not have a static 'Parser' property."); } MessageParser? parser = parserProperty.GetValue(null) as MessageParser; if (parser == null) { throw new InvalidOperationException($"Could not get MessageParser for type {typeof(T).Name}."); } return parser.ParseFrom(data); } public static Request CreateRequest(uint id, CommandType commandType, T payloadMessage) where T : IMessage { return new Request { Id = id, Type = commandType, Payload = ByteString.CopyFrom(Serialize(payloadMessage)) }; } public static Response CreateResponse(uint id, bool success, string? errorMessage, T payloadMessage) where T : IMessage { return new Response { Id = id, Success = success, Message = errorMessage ?? string.Empty, Payload = ByteString.CopyFrom(Serialize(payloadMessage)) }; } public static Response CreateErrorResponse(uint id, string errorMessage) { return new Response { Id = id, Success = false, Message = errorMessage }; } public static T ExtractPayload(Request request) where T : IMessage, new() { if (request == null) { throw new ArgumentNullException(nameof(request), "Request cannot be null."); } if (request.Payload == null || request.Payload.IsEmpty) { throw new ArgumentNullException(nameof(request.Payload), "Request payload is null or empty."); } return Deserialize(request.Payload.ToByteArray()); } public static T ExtractPayload(Response response) where T : IMessage, new() { if (response == null) { throw new ArgumentNullException(nameof(response), "Response cannot be null."); } if (response.Payload == null || response.Payload.IsEmpty) { throw new ArgumentNullException(nameof(response.Payload), "Response payload is null or empty."); } return Deserialize(response.Payload.ToByteArray()); } } }