Files
2026-07-05 14:29:29 +08:00

134 lines
4.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace ISphereWinHelper
{
internal static class HelperProtocol
{
public const string Protocol = "isphere.helper.v1";
private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer { MaxJsonLength = 16 * 1024 * 1024, RecursionLimit = 256 };
public static bool TryParseRequest(string text, out Dictionary<string, object> request, out string requestId, out string op)
{
request = null;
requestId = "";
op = "";
if (string.IsNullOrWhiteSpace(text))
{
return false;
}
try
{
object decoded = Serializer.DeserializeObject(text);
request = decoded as Dictionary<string, object>;
if (request == null)
{
return false;
}
string protocol = GetString(request, "protocol", "");
requestId = GetString(request, "request_id", "");
op = GetString(request, "op", "");
if (protocol != Protocol || string.IsNullOrWhiteSpace(op))
{
return false;
}
return true;
}
catch
{
return false;
}
}
public static Dictionary<string, object> Success(string requestId, string op, object data)
{
return Envelope(requestId, op, true, data, null);
}
public static Dictionary<string, object> Failure(string requestId, string op, string code, string message)
{
var error = new Dictionary<string, object>
{
{ "code", code },
{ "message", message }
};
return Envelope(requestId, op, false, null, error);
}
private static Dictionary<string, object> Envelope(string requestId, string op, bool ok, object data, object error)
{
return new Dictionary<string, object>
{
{ "protocol", Protocol },
{ "request_id", requestId ?? "" },
{ "op", op ?? "" },
{ "ok", ok },
{ "data", data },
{ "error", error },
{ "warnings", new object[0] }
};
}
public static string ToJson(object value)
{
return Serializer.Serialize(value);
}
public static Dictionary<string, object> GetObject(Dictionary<string, object> source, string key)
{
if (source == null || !source.ContainsKey(key) || source[key] == null)
{
return new Dictionary<string, object>();
}
return source[key] as Dictionary<string, object> ?? new Dictionary<string, object>();
}
public static string GetString(Dictionary<string, object> source, string key, string defaultValue)
{
if (source == null || !source.ContainsKey(key) || source[key] == null)
{
return defaultValue;
}
return Convert.ToString(source[key]);
}
public static bool GetBool(Dictionary<string, object> source, string key, bool defaultValue)
{
if (source == null || !source.ContainsKey(key) || source[key] == null)
{
return defaultValue;
}
try
{
return Convert.ToBoolean(source[key]);
}
catch
{
return defaultValue;
}
}
public static int GetInt(Dictionary<string, object> source, string key, int defaultValue)
{
if (source == null || !source.ContainsKey(key) || source[key] == null)
{
return defaultValue;
}
try
{
return Convert.ToInt32(source[key]);
}
catch
{
return defaultValue;
}
}
}
}