| | 1 | | using System.Text.RegularExpressions; |
| | 2 | |
|
| | 3 | | namespace ValidateLib.Metadata.MetdataLocation |
| | 4 | | { |
| | 5 | | /// <summary> |
| | 6 | | /// Processes HTTP link headers and extracts possible metadata locations. |
| | 7 | | /// </summary> |
| | 8 | | public class LinkHeaderProcessor : ILinkHeaderProcessor |
| | 9 | | { |
| 1 | 10 | | static Regex linkHeaderRegex = new Regex(@"<([^>]+)>;\s*(?:rel=""([^""]+)"";\s*type=""([^""]+)""|type=""([^""]+) |
| | 11 | | public static List<string> GetMetadataLocationsFromLinkHeader(HttpResponseMessage response) |
| | 12 | | { |
| 1 | 13 | | List<string> locations = new List<string>(); |
| | 14 | | // Check if the request was successful |
| 1 | 15 | | if (response.IsSuccessStatusCode) |
| | 16 | | { |
| | 17 | |
|
| | 18 | | // Check for Link headers |
| 1 | 19 | | if (response.Headers.TryGetValues("Link", out var linkHeaderValues)) |
| | 20 | | { |
| 1 | 21 | | ProcessLinkHeaderValues(linkHeaderValues, locations); |
| | 22 | | } |
| | 23 | | } |
| | 24 | |
|
| 1 | 25 | | return locations; |
| | 26 | | } |
| | 27 | | static void ProcessLinkHeaderValues(IEnumerable<string> linkHeaderValues, List<string> locations) |
| | 28 | | { |
| 1 | 29 | | foreach (var linkHeaderValue in linkHeaderValues) |
| | 30 | | { |
| 1 | 31 | | var matches = linkHeaderRegex.Matches(linkHeaderValue); |
| 1 | 32 | | for (int i = 0; i < matches.Count; i++) |
| | 33 | | { |
| 1 | 34 | | var match = matches[i]; |
| 1 | 35 | | var url = match.Groups[1].Value; |
| 1 | 36 | | var rel = match.Groups[2].Success ? match.Groups[2].Value : match.Groups[4].Value; |
| 1 | 37 | | var type = match.Groups[3].Success ? match.Groups[3].Value : match.Groups[5].Value; |
| 1 | 38 | | if (isValidLinkHeader(url, rel, type)) |
| 1 | 39 | | locations.Add(url); |
| | 40 | | } |
| | 41 | | } |
| 1 | 42 | | } |
| | 43 | | static bool isValidLinkHeader(string? url, string? rel, string? type) |
| | 44 | | { |
| 1 | 45 | | string[] validTypes = new string[] |
| 1 | 46 | | { |
| 1 | 47 | | "application/csvm+json", |
| 1 | 48 | | "application/ld+json", |
| 1 | 49 | | "application/json" |
| 1 | 50 | | }; |
| 1 | 51 | | if (url is null || rel is null || type is null) |
| 0 | 52 | | return false; |
| 1 | 53 | | if (rel == "describedby" && validTypes.Contains(type)) |
| 1 | 54 | | return true; |
| 0 | 55 | | return false; |
| | 56 | | } |
| | 57 | | class LinkHeader |
| | 58 | | { |
| 0 | 59 | | public string Url { get; } |
| 0 | 60 | | public string RelationType { get; } |
| 0 | 61 | | public string MediaType { get; } |
| | 62 | |
|
| 0 | 63 | | public LinkHeader(string url, string relationType, string mediaType) |
| | 64 | | { |
| 0 | 65 | | Url = url; |
| 0 | 66 | | RelationType = relationType; |
| 0 | 67 | | MediaType = mediaType; |
| 0 | 68 | | } |
| | 69 | | } |
| | 70 | |
|
| | 71 | | } |
| | 72 | | } |