using System.Collections.Concurrent; using System.Security.Cryptography; using System.Text; using System.Text.Json; namespace XFEWarframe.Client; /// Original game icons and native-rendered card PNGs. Full cards are never substituted with artwork. public static class VisualAssetCache { public static string Root { get; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XFEWarframe", "VisualAssets"); private static readonly HttpClient Http = new(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(10) }; private static readonly ConcurrentDictionary>> Pending = new(); private static readonly Lazy>> Manifest = new(() => Task.Run(ReadManifest)); public static string Key(string kind, string resource, string fingerprint = "", string language = "zh", string build = "2026.08.19.11.06") => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(kind + "\n" + build + "\n" + language + "\n" + resource + "\n" + (kind.StartsWith("card-", StringComparison.Ordinal) ? CanonicalFingerprint(fingerprint) : fingerprint)))); public static string? Find(string key) => ValidKey(key) && File.Exists(Path.Combine(Root, key + ".png")) ? Path.Combine(Root, key + ".png") : null; public static async Task IconAsync(string resource) { var key = Key("icon", resource); var request = Pending.GetOrAdd(key, _ => new(() => FetchIcon(resource), LazyThreadSafetyMode.ExecutionAndPublication)); try { return await request.Value.ConfigureAwait(false); } finally { Pending.TryRemove(new KeyValuePair>>(key, request)); } } private static async Task FetchIcon(string resource) { var key = Key("icon", resource); var cached = Find(key); if (cached is not null) return cached; try { if (!resource.StartsWith("/Lotus/Interface/", StringComparison.Ordinal) || !(await Manifest.Value.ConfigureAwait(false)).TryGetValue(resource, out var hash)) return null; using var response = await Http.GetAsync("https://content.warframe.com/PublicExport" + resource + "!" + hash, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); if (!response.IsSuccessStatusCode || response.Content.Headers.ContentLength > 4_000_000) return null; await using var input = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); using var bytes = new MemoryStream(); var buffer = new byte[16384]; int length; while ((length = await input.ReadAsync(buffer).ConfigureAwait(false)) != 0) { if (bytes.Length + length > 4_000_000) return null; await bytes.WriteAsync(buffer.AsMemory(0, length)).ConfigureAwait(false); } return await StoreAsync(key, bytes.ToArray()).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or HttpRequestException or OperationCanceledException or JsonException) { return null; } } public static async Task StoreAsync(string key, byte[] png, CancellationToken cancellation = default) { if (!ValidKey(key)) throw new InvalidDataException("Invalid native image cache key."); PngImages.Validate(png); Directory.CreateDirectory(Root); var destination = Path.Combine(Root, key + ".png"); var temporary = destination + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { await File.WriteAllBytesAsync(temporary, png, cancellation).ConfigureAwait(false); File.Move(temporary, destination, true); } finally { if (File.Exists(temporary)) File.Delete(temporary); } return destination; } private static bool ValidKey(string key) => key.Length == 64 && key.All(Uri.IsHexDigit); private static string CanonicalFingerprint(string fingerprint) { if (string.IsNullOrWhiteSpace(fingerprint)) return "{\"lvl\":0}"; try { using var document = JsonDocument.Parse(fingerprint); if (document.RootElement.ValueKind != JsonValueKind.Object) return fingerprint; using var bytes = new MemoryStream(); using (var writer = new Utf8JsonWriter(bytes)) Write(document.RootElement, writer, true); return Encoding.UTF8.GetString(bytes.ToArray()); } catch (JsonException) { return fingerprint; } static void Write(JsonElement element, Utf8JsonWriter writer, bool root = false) { if (element.ValueKind == JsonValueKind.Object) { writer.WriteStartObject(); if (root) { writer.WritePropertyName("lvl"); if (element.TryGetProperty("lvl", out var level)) level.WriteTo(writer); else writer.WriteNumberValue(0); } foreach (var property in element.EnumerateObject().Where(x => !root || x.Name != "lvl").OrderBy(x => x.Name, StringComparer.Ordinal)) { writer.WritePropertyName(property.Name); Write(property.Value, writer); } writer.WriteEndObject(); } else if (element.ValueKind == JsonValueKind.Array) { writer.WriteStartArray(); foreach (var child in element.EnumerateArray()) Write(child, writer); writer.WriteEndArray(); } else element.WriteTo(writer); } } private static IReadOnlyDictionary ReadManifest() { using var stream = typeof(VisualAssetCache).Assembly.GetManifestResourceStream("XFEWarframe.VisualImages.json") ?? throw new InvalidDataException("Missing game image manifest."); using var json = JsonDocument.Parse(stream); return json.RootElement.EnumerateObject().Where(x => x.Value.TryGetProperty("contentHash", out _)) .ToDictionary(x => x.Name, x => x.Value.GetProperty("contentHash").GetString()!, StringComparer.Ordinal); } }