using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using Manager.YouTube.Models.Innertube; namespace Manager.YouTube.Parsers.Json; public static class JsonParser { public static List ParseImages(JsonElement.ArrayEnumerator array) => array .Select(image => new WebImage { Width = image.GetProperty("width").GetInt32(), Height = image.GetProperty("height").GetInt32(), Url = image.GetProperty("url").GetString() ?? "" }) .ToList(); public static string ExtractTextOrHtml(JsonNode? node) { if (node is not JsonObject nodeObj) { return ""; } // Case 1: Simple text (no formatting) if (nodeObj.TryGetPropertyValue("simpleText", out var simpleText)) return simpleText?.GetValue() ?? string.Empty; // Case 2: Runs (formatted text segments) if (nodeObj.TryGetPropertyValue("runs", out var runs) && runs != null && runs.GetValueKind() == JsonValueKind.Array) { var sb = new StringBuilder(); foreach (var runNode in runs.AsArray()) { if (runNode is not JsonObject run) { continue; } var text = runNode["text"]?.GetValue() ?? string.Empty; var formatted = System.Net.WebUtility.HtmlEncode(text); var bold = run.TryGetPropertyValue("bold", out var boldNode) && boldNode is JsonValue bv && bv.GetValue(); var italic = run.TryGetPropertyValue("italic", out var italicNode) && italicNode is JsonValue iv && iv.GetValue(); var underline = run.TryGetPropertyValue("underline", out var underlineNode) && underlineNode is JsonValue uv && uv.GetValue(); var strikethrough = run.TryGetPropertyValue("strikethrough", out var strikeNode) && strikeNode is JsonValue sv && sv.GetValue(); if (bold) formatted = $"{formatted}"; if (italic) formatted = $"{formatted}"; if (underline) formatted = $"{formatted}"; if (strikethrough) formatted = $"{formatted}"; if (run.TryGetPropertyValue("navigationEndpoint", out var nav) && nav is JsonObject navObj && navObj.TryGetPropertyValue("url", out var urlProp)) { var url = urlProp?.GetValue(); if (!string.IsNullOrEmpty(url)) formatted = $"{formatted}"; } if (run.TryGetPropertyValue("emoji", out var emoji) && emoji is JsonObject emojiObj) { if (emojiObj.TryGetPropertyValue("url", out var emojiUrl)) { var src = emojiUrl?.GetValue(); if (!string.IsNullOrEmpty(src)) formatted = $"\"{text}\""; } } sb.Append(formatted); } return sb.ToString(); } return string.Empty; } public static List ExtractWebImages(JsonNode? node) { if (node == null) { return []; } var thumbnailsArray = node["thumbnails"]; return thumbnailsArray?.Deserialize>() ?? []; } }