| | | 1 | | using System.Text.Json; |
| | | 2 | | |
| | | 3 | | namespace Chronicis.Api.Services.ExternalLinks; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Minimal helper for extracting guaranteed fields from SRD JSON blobs. |
| | | 7 | | /// Only extracts fields guaranteed by the blob schema: pk and fields.name. |
| | | 8 | | /// </summary> |
| | | 9 | | internal static class SrdJsonHelper |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// Extracts the title from fields.name, with fallback to prettified slug. |
| | | 13 | | /// </summary> |
| | | 14 | | /// <param name="json">Parsed JSON document.</param> |
| | | 15 | | /// <param name="fallbackSlug">Slug to prettify if fields.name is missing.</param> |
| | | 16 | | /// <returns>Title string.</returns> |
| | | 17 | | public static string ExtractTitle(JsonDocument json, string fallbackSlug) |
| | | 18 | | { |
| | | 19 | | try |
| | | 20 | | { |
| | 0 | 21 | | var root = json.RootElement; |
| | | 22 | | |
| | | 23 | | // Try to get fields.name |
| | 0 | 24 | | if (root.TryGetProperty("fields", out var fields) && |
| | 0 | 25 | | fields.TryGetProperty("name", out var nameElement) && |
| | 0 | 26 | | nameElement.ValueKind == JsonValueKind.String) |
| | | 27 | | { |
| | 0 | 28 | | var name = nameElement.GetString(); |
| | 0 | 29 | | if (!string.IsNullOrWhiteSpace(name)) |
| | | 30 | | { |
| | 0 | 31 | | return name; |
| | | 32 | | } |
| | | 33 | | } |
| | 0 | 34 | | } |
| | 0 | 35 | | catch |
| | | 36 | | { |
| | | 37 | | // Parsing failed, use fallback |
| | 0 | 38 | | } |
| | | 39 | | |
| | | 40 | | // Fallback: prettify slug |
| | 0 | 41 | | return BlobFilenameParser.PrettifySlug(fallbackSlug); |
| | 0 | 42 | | } |
| | | 43 | | |
| | | 44 | | /// <summary> |
| | | 45 | | /// Extracts the optional pk field for debugging purposes. |
| | | 46 | | /// </summary> |
| | | 47 | | public static string? ExtractPk(JsonDocument json) |
| | | 48 | | { |
| | | 49 | | try |
| | | 50 | | { |
| | 0 | 51 | | var root = json.RootElement; |
| | 0 | 52 | | if (root.TryGetProperty("pk", out var pkElement) && |
| | 0 | 53 | | pkElement.ValueKind == JsonValueKind.String) |
| | | 54 | | { |
| | 0 | 55 | | return pkElement.GetString(); |
| | | 56 | | } |
| | 0 | 57 | | } |
| | 0 | 58 | | catch |
| | | 59 | | { |
| | | 60 | | // Ignore parsing errors |
| | 0 | 61 | | } |
| | | 62 | | |
| | 0 | 63 | | return null; |
| | 0 | 64 | | } |
| | | 65 | | } |