using System.Collections.Concurrent; using Newtonsoft.Json.Linq; using XFEWarframe.Core.Data; namespace XFEWarframe.Core.Services; public static class Avatars { public const string DefaultType = "/Lotus/Types/StoreItems/AvatarImages/AvatarImageDefault"; private static readonly Lazy Manifest = new(() => (JObject)Assets.Json("avatar-manifest.json")); private static readonly HttpClient Http = new(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(8) }; private static readonly ConcurrentDictionary Cache = new(); public static string Type(JObject account) => account.Obj("Inventory").Value("ActiveAvatarImageType") ?? DefaultType; public static async Task Image(string type, ServerOptions options) { var icon = GameData.Find("Flavour", type)?.Value("icon"); if (icon is not null && icon.StartsWith("/Lotus/Interface/", StringComparison.Ordinal)) { var local = await new ContentApi(options).Handle("publicExportTexture", new("GET", "/PublicExport" + icon, new Dictionary())); if (local.Status == 200) return local; } if (type == DefaultType) return ApiResponse.Binary(Assets.Binary("avatar-default.png"), "image/png"); if (Cache.TryGetValue(type, out var cached)) return ApiResponse.Binary(cached, "image/png"); var texture = Manifest.Value.Value(type); if (texture is null) return ApiResponse.Text("", 404); try { using var response = await Http.GetAsync("https://content.warframe.com/PublicExport" + texture, HttpCompletionOption.ResponseHeadersRead); if (!response.IsSuccessStatusCode || response.Content.Headers.ContentLength is > 2_000_000) return ApiResponse.Text("", 404); using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(8)); await using var stream = await response.Content.ReadAsStreamAsync(timeout.Token); using var bytes = new MemoryStream(); var buffer = new byte[8192]; int read; while ((read = await stream.ReadAsync(buffer, timeout.Token)) != 0) { if (bytes.Length + read > 2_000_000) return ApiResponse.Text("", 404); bytes.Write(buffer, 0, read); } var image = bytes.ToArray(); if (image.Length < 8 || !image.AsSpan(0, 8).SequenceEqual(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 })) return ApiResponse.Text("", 404); if (Cache.Count < 64) Cache.TryAdd(type, image); return ApiResponse.Binary(image, "image/png"); } catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException) { return ApiResponse.Text("", 404); } } }