using System.Globalization; using System.Buffers.Binary; using System.Security.Cryptography; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace XFEWarframe.Core; public sealed class ApiException(int status, string message) : Exception(message) { public int Status { get; } = status; } public sealed record ApiRequest(string Method, string Path, IReadOnlyDictionary Query, string Body = "", string? AdminToken = null, string ClientIp = "127.0.0.1") { public string? Q(string name) => Query.GetValueOrDefault(name); public JObject ObjectBody() { if (string.IsNullOrWhiteSpace(Body)) return new(); try { return JObject.Parse(Body); } catch (JsonException) { throw new ApiException(400, "Expected a JSON object"); } } } public sealed record ApiResponse(int Status, string Body, string ContentType = "application/json; charset=utf-8") { public byte[]? BinaryBody { get; init; } public static ApiResponse Binary(byte[] value, string contentType = "application/octet-stream") => new(200, "", contentType) { BinaryBody = value }; public static ApiResponse Json(object? value, int status = 200) => new(status, JsonConvert.SerializeObject(value, Formatting.None, Wire.Settings)); public static ApiResponse Text(string value = "", int status = 200) => new(status, value, "text/plain; charset=utf-8"); } public static class Wire { public static readonly JsonSerializerSettings Settings = new() { DateParseHandling = DateParseHandling.None }; public static JObject ReadObject(string json) => JsonConvert.DeserializeObject(json, Settings) ?? new(); private static readonly byte[] ProcessId = RandomNumberGenerator.GetBytes(5); private static int objectCounter = RandomNumberGenerator.GetInt32(0x1000000); // Mongo ObjectId layout keeps incremental inbox requests ordered within a process. public static string NewId() { Span bytes = stackalloc byte[12]; BinaryPrimitives.WriteUInt32BigEndian(bytes, (uint)DateTimeOffset.UtcNow.ToUnixTimeSeconds()); ProcessId.CopyTo(bytes[4..9]); var counter = Interlocked.Increment(ref objectCounter); bytes[9] = (byte)(counter >> 16); bytes[10] = (byte)(counter >> 8); bytes[11] = (byte)counter; return Convert.ToHexStringLower(bytes); } public static JObject Oid(string id) => new() { ["$oid"] = id }; public static string Id(JToken? token) => token is JObject obj ? obj.Value("$oid") ?? obj.Value("$id") ?? "" : token?.ToString() ?? ""; public static JObject Date(long ms) => new() { ["$date"] = new JObject { ["$numberLong"] = ms.ToString(CultureInfo.InvariantCulture) } }; public static long DateMs(JToken? token) { if (token is JObject legacy && legacy["sec"] is not null) return checked(legacy.Value("sec") * 1000 + legacy.Value("usec") / 1000); if (token is JObject wrapper) token = wrapper["$date"]; if (token is JObject number) token = number["$numberLong"]; if (long.TryParse(token?.ToString(), out var ms)) return ms; return DateTimeOffset.TryParse(token?.ToString(), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var date) ? date.ToUnixTimeMilliseconds() : 0; } public static long Nonce() => (BitConverter.ToInt64(RandomNumberGenerator.GetBytes(8)) & 0x1fffffffffffffL) | 1; public static long Seed() => BitConverter.ToInt64(RandomNumberGenerator.GetBytes(8)); public static bool SecretEquals(string? actual, string? expected) => actual is not null && expected is not null && CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(actual)), SHA256.HashData(Encoding.UTF8.GetBytes(expected))); public static JArray Array(this JObject obj, string key) { if (obj[key] is not JArray) obj[key] = new JArray(); return (JArray)obj[key]!; } public static JObject Obj(this JObject obj, string key) { if (obj[key] is not JObject) obj[key] = new JObject(); return (JObject)obj[key]!; } public static string RequiredString(this JObject obj, string key, int max = 1024) { if (obj[key]?.Type != JTokenType.String || string.IsNullOrWhiteSpace(obj.Value(key)) || obj.Value(key)!.Length > max) throw new ApiException(400, $"Invalid {key}"); return obj.Value(key)!; } public static long Integer(this JObject obj, string key, long min = 0, long max = 999_999_999) { if (obj[key]?.Type != JTokenType.Integer || !long.TryParse(obj[key]!.ToString(), out var value) || value < min || value > max) throw new ApiException(400, $"Invalid {key}"); return value; } public static void UniqueAdd(this JArray array, JToken token) { if (!array.Any(x => JToken.DeepEquals(x, token))) array.Add(token.DeepClone()); } }