56 lines
1.8 KiB
C#
56 lines
1.8 KiB
C#
using ModVersionChecker.data.model;
|
|
using System;
|
|
using System.Net.Http;
|
|
using System.Text.Json;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace ModVersionChecker
|
|
{
|
|
public class ApiChecker : IVersionChecker
|
|
{
|
|
private static readonly HttpClient _httpClient = new HttpClient();
|
|
|
|
public async Task<string> GetLatestVersion(Dictionary<string, string> paramsDict, SourceDef source)
|
|
{
|
|
if (!paramsDict.TryGetValue("url", out var url) || string.IsNullOrEmpty(url))
|
|
{
|
|
throw new ArgumentException("API URL required");
|
|
}
|
|
if (!paramsDict.TryGetValue("jsonPath", out var jsonPath) || string.IsNullOrEmpty(jsonPath))
|
|
{
|
|
throw new ArgumentException("jsonPath required");
|
|
}
|
|
|
|
var response = await _httpClient.GetAsync(url);
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
throw new Exception($"API error: {(int)response.StatusCode} {response.ReasonPhrase}");
|
|
}
|
|
|
|
var body = await response.Content.ReadAsStringAsync();
|
|
if (string.IsNullOrEmpty(body))
|
|
{
|
|
throw new Exception("Empty API response");
|
|
}
|
|
|
|
using var jsonDoc = JsonDocument.Parse(body);
|
|
var element = jsonDoc.RootElement;
|
|
|
|
foreach (var key in jsonPath.Split('.'))
|
|
{
|
|
if (!element.TryGetProperty(key, out var nextElement))
|
|
{
|
|
throw new Exception($"JSON key '{key}' not found in response");
|
|
}
|
|
element = nextElement;
|
|
}
|
|
|
|
if (element.ValueKind != JsonValueKind.String)
|
|
{
|
|
throw new Exception($"JSON value for '{jsonPath}' is not a string");
|
|
}
|
|
|
|
return element.GetString()!.Trim();
|
|
}
|
|
}
|
|
} |