This commit is contained in:
Jose Conde
2025-09-29 16:02:00 +02:00
parent dc57da8136
commit 5e16f781b4
74 changed files with 1621 additions and 1856 deletions

View File

@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModVersionChecker.repository.api
{
public class ApiBase: IDisposable
{
private readonly HttpClient _httpClient = new HttpClient();
public ApiBase()
{
_httpClient.Timeout = TimeSpan.FromSeconds(30);
_httpClient.DefaultRequestHeaders.Add("User-Agent", "ModVersionChecker");
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
}

View File

@@ -0,0 +1,169 @@
using ModVersionChecker.repository.api.dto;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ModVersionChecker.repository.api
{
public class ApiRepository : IApiRepository, IDisposable
{
private readonly HttpClient _httpClient;
private string baseUrl = "http://192.168.1.115:3115/api";
private JwtTokenResponse? _accessToken;
private JwtTokenResponse? _refreshToken;
private DateTime _accessTokenExpiry = DateTime.MinValue;
public ApiRepository()
{
_httpClient = new HttpClient();
_httpClient.Timeout = TimeSpan.FromSeconds(30);
}
public async Task<bool> AuthenticateAsync(string username, string password)
{
var url = $"{baseUrl}/auth";
var payload = new { username, password };
var jsonPayload = JsonSerializer.Serialize(payload);
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
try
{
var response = await _httpClient.PostAsync(url, content);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
var authentication = JsonSerializer.Deserialize<AuthenticationResponse>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
_accessToken = DecodeJwt(authentication?.AccessToken);
_refreshToken = DecodeJwt(authentication?.RefreshToken);
if (_accessToken == null)
throw new Exception("Failed to decode access token.");
_accessTokenExpiry = DateTime.UtcNow.AddSeconds(_accessToken.ExpireAt - 60);
return true;
}
catch
{
return false;
}
}
private JwtTokenResponse? DecodeJwt(string? token)
{
if (string.IsNullOrEmpty(token))
return null;
var parts = token.Split('.');
if (parts.Length != 3)
throw new ArgumentException("Invalid JWT token format.");
var payload = parts[1];
var paddedPayload = payload.PadRight(payload.Length + (4 - payload.Length % 4) % 4, '=');
var jsonBytes = Convert.FromBase64String(paddedPayload);
var json = Encoding.UTF8.GetString(jsonBytes);
var doc = JsonSerializer.Deserialize<JwtTokenResponse>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (doc != null)
doc.Token = token;
return doc;
}
private async Task<bool> EnsureTokenValidAsync()
{
if (_accessToken == null || DateTime.UtcNow >= _accessTokenExpiry)
{
return await RefreshTokenAsync();
}
return true;
}
private async Task<bool> RefreshTokenAsync()
{
if (_refreshToken == null)
return false;
var refreshData = new { refreshToken = _refreshToken };
var content = new StringContent(JsonSerializer.Serialize(refreshData), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync($"{baseUrl}/auth/refresh", content);
if (!response.IsSuccessStatusCode)
return false;
var json = await response.Content.ReadAsStringAsync();
var authentication = JsonSerializer.Deserialize<AuthenticationResponse>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
_accessToken = DecodeJwt(authentication?.AccessToken);
if (_accessToken == null)
throw new Exception("Failed to decode access token.");
_accessTokenExpiry = DateTime.UtcNow.AddSeconds(_accessToken.ExpireAt - 60);
return true;
}
private async Task<HttpRequestMessage> CreateRequestAsync(HttpMethod method, string url)
{
await EnsureTokenValidAsync();
var request = new HttpRequestMessage(method, url);
if (_accessToken != null)
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken.Token);
return request;
}
public async Task<List<AppVersionsResponse>?> GetAppVersionsAsync(List<App> apps)
{
var url = $"{baseUrl}/app/versions?{string.Join("&", apps.Select(a => $"version={Uri.EscapeDataString(a.Id)}"))}";
var request = await CreateRequestAsync(HttpMethod.Get, url);
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<List<AppVersionsResponse>>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
public async Task<AppVersionsResponse?> GetAppLatestVersionAsync(App app)
{
var url = $"{baseUrl}/app/latest?version={Uri.EscapeDataString(app.Id)}";
var request = await CreateRequestAsync(HttpMethod.Get, url);
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<AppVersionsResponse>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
public async Task<List<TypeResponse>> GetTypes()
{
var url = $"{baseUrl}/type";
var request = await CreateRequestAsync(HttpMethod.Get, url);
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<List<TypeResponse>>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
public async Task<List<SourceResponse>> GetSources()
{
var url = $"{baseUrl}/source";
var request = await CreateRequestAsync(HttpMethod.Get, url);
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<List<SourceResponse>>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
public async Task<List<AppResponse>?> SearchApps(string searchText)
{
var url = $"{baseUrl}/app/search?query={Uri.EscapeDataString(searchText)}";
var request = await CreateRequestAsync(HttpMethod.Get, url);
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<List<AppResponse>>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
public async Task<List<AppResponse>> GetAppsByIds(App[] apps)
{
var query = string.Join("&", apps.Select(a => $"id={Uri.EscapeDataString(a.Id)}"));
var url = $"{baseUrl}/app/search?{query}";
var request = await CreateRequestAsync(HttpMethod.Get, url);
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<List<AppResponse>>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new List<AppResponse>();
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
}

View File

@@ -0,0 +1,17 @@
using System.Threading.Tasks;
using System.Collections.Generic;
using ModVersionChecker.repository.api.dto;
namespace ModVersionChecker.repository.api
{
public interface IApiRepository
{
Task<bool> AuthenticateAsync(string username, string password);
Task<List<AppVersionsResponse>?> GetAppVersionsAsync(List<App> apps);
Task<AppVersionsResponse?> GetAppLatestVersionAsync(App app);
Task<List<AppResponse>?> SearchApps(string searchText);
Task<List<TypeResponse>> GetTypes();
Task<List<SourceResponse>> GetSources();
Task<List<AppResponse>> GetAppsByIds(App[] apps);
}
}

View File

@@ -0,0 +1,81 @@
using ModVersionChecker.enums;
using System.Text.Json.Serialization;
namespace ModVersionChecker.repository.api.dto
{
public class AppResponse
{
public AppResponse() { }
[JsonPropertyName("id")]
public string Id { get; set; } = string.Empty;
[JsonPropertyName("uid")]
public string Uid { get; set; } = string.Empty;
[JsonPropertyName("name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("type")]
public string Type { get; set; } = string.Empty;
[JsonPropertyName("source")]
public string Source { get; set; } = string.Empty;
[JsonPropertyName("params")]
public Dictionary<string, string> Params { get; set; } = new Dictionary<string, string>();
[JsonPropertyName("fields")]
public Dictionary<string, string> Fields { get; set; } = new Dictionary<string, string>();
[JsonPropertyName("downloadUrl")]
public string DownloadUrl { get; set; } = string.Empty;
[JsonPropertyName("currentVersion")]
public string CurrentVersion { get; set; } = string.Empty;
[JsonPropertyName("latestVersion")]
public string LatestVersion { get; set; } = string.Empty;
[JsonPropertyName("status")]
[JsonConverter(typeof(JsonStringEnumConverter))]
public AppStatus Status { get; set; } = AppStatus.NONE;
[JsonPropertyName("createdAt")]
public long CreatedAt { get; set; } = 0;
[JsonPropertyName("updatedAt")]
public long UpdatedAt { get; set; } = 0;
[JsonPropertyName("lastCheckedAt")]
public long LastCheckedAt { get; set; } = 0;
[JsonPropertyName("active")]
public bool Active { get; set; } = false;
public static App toModel(AppResponse appResponse)
{
if (appResponse == null)
{
return new App();
}
return new App()
{
Id = appResponse.Id,
Uid = appResponse.Uid,
Name = appResponse.Name,
Type = appResponse.Type,
Source = appResponse.Source,
Params = appResponse.Params,
Fields = appResponse.Fields,
DownloadUrl = appResponse.DownloadUrl,
CurrentVersion = appResponse.CurrentVersion,
LatestVersion = appResponse.LatestVersion,
Status = appResponse.Status,
LastCheckedAt = appResponse.LastCheckedAt,
};
}
}
}

View File

@@ -0,0 +1,15 @@
using System.Text.Json.Serialization;
namespace ModVersionChecker.repository.api.dto
{
public class AppVersionsResponse
{
public AppVersionsResponse() { }
[JsonPropertyName("id")]
public string Id { get; set; } = string.Empty;
[JsonPropertyName("latestVersion")]
public string LatestVersion { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace ModVersionChecker.repository.api.dto
{
public class AuthenticationResponse
{
[JsonPropertyName("accessToken")]
public string AccessToken { get; set; } = string.Empty;
[JsonPropertyName("refreshToken")]
public string RefreshToken { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace ModVersionChecker.repository.api.dto
{
public class FieldResponse
{
[JsonPropertyName("name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("label")]
public string Label { get; set; } = string.Empty;
[JsonPropertyName("description")]
public string Description { get; set; } = string.Empty;
[JsonPropertyName("type")]
public string Type { get; set; } = string.Empty;
[JsonPropertyName("required")]
public bool Required { get; set; } = false;
[JsonPropertyName("controlType")]
public string ControlType { get; set; } = string.Empty;
[JsonPropertyName("defaultValue")]
public string DefaultValue { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace ModVersionChecker.repository.api.dto
{
public class JwtTokenResponse
{
public JwtTokenResponse() { }
public string Token { get; set; } = string.Empty;
[JsonPropertyName("exp")]
public long ExpireAt { get; set; } = 0;
[JsonPropertyName("iat")]
public long IssuedAt { get; set; } = 0;
[JsonPropertyName("sub")]
public string Subject { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,19 @@
using System.Text.Json.Serialization;
namespace ModVersionChecker.repository.api.dto
{
public class SourceResponse
{
[JsonPropertyName("id")]
public string Id { get; set; } = string.Empty;
[JsonPropertyName("name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("type")]
public string Type { get; set; } = string.Empty;
[JsonPropertyName("defaults")]
public Dictionary<string, string> Defaults { get; set; } = new Dictionary<string, string>();
}
}

View File

@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace ModVersionChecker.repository.api.dto
{
public class TypeResponse
{
public string Id { get; set; } = String.Empty;
[JsonPropertyName("name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("shortName")]
public string ShortName { get; set; } = string.Empty;
[JsonPropertyName("configFields")]
public List<FieldResponse> ConfigFields { get; set; } = new List<FieldResponse>();
[JsonPropertyName("appFields")]
public List<FieldResponse> AppFields { get; set; } = new List<FieldResponse>();
}
}