using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; namespace Heimdall.Web.Services; public class HeimdallApiClient { private readonly IHttpClientFactory _httpFactory; private readonly AuthState _authState; private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; public HeimdallApiClient(IHttpClientFactory httpFactory, AuthState authState) { _httpFactory = httpFactory; _authState = authState; } private HttpClient CreateClient() { var client = _httpFactory.CreateClient("HeimdallApi"); if (_authState.AccessToken is not null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _authState.AccessToken); return client; } // ─── Auth ───────────────────────────────────────────────────── public async Task LoginAsync(string email, string password) { var client = CreateClient(); var response = await client.PostAsJsonAsync("api/auth/login", new { email, password }); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(Json); } public async Task RegisterAsync(string email, string password, string displayName) { var client = CreateClient(); var response = await client.PostAsJsonAsync("api/auth/register", new { email, password, displayName }); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(Json); } // ─── Users ──────────────────────────────────────────────────── public async Task?> GetUsersAsync(int page = 1, int pageSize = 20) { var client = CreateClient(); return await client.GetFromJsonAsync>( $"api/users?page={page}&pageSize={pageSize}", Json); } public async Task GetUserAsync(Guid id) { var client = CreateClient(); return await client.GetFromJsonAsync($"api/users/{id}", Json); } public async Task CreateUserAsync(string email, string password, string displayName, IList roles) { var client = CreateClient(); var response = await client.PostAsJsonAsync("api/users", new { email, password, displayName, roles }, Json); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(Json); } public async Task UpdateUserAsync(Guid id, string displayName, string? theme, string? language) { var client = CreateClient(); var response = await client.PutAsJsonAsync($"api/users/{id}", new { displayName, theme, language }, Json); return response.IsSuccessStatusCode; } public async Task AssignRolesAsync(Guid userId, IList roles) { var client = CreateClient(); var response = await client.PutAsJsonAsync($"api/users/{userId}/roles", new { roles }, Json); return response.IsSuccessStatusCode; } public async Task AssignSitesAsync(Guid userId, IList siteIds) { var client = CreateClient(); var response = await client.PutAsJsonAsync($"api/users/{userId}/sites", new { siteIds }, Json); return response.IsSuccessStatusCode; } public async Task ResetPasswordAsync(Guid userId) { var client = CreateClient(); var response = await client.PostAsync($"api/users/{userId}/reset-password", null); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(Json); } public async Task LockUserAsync(Guid userId) { var client = CreateClient(); var response = await client.PostAsync($"api/users/{userId}/lock", null); return response.IsSuccessStatusCode; } public async Task UnlockUserAsync(Guid userId) { var client = CreateClient(); var response = await client.PostAsync($"api/users/{userId}/unlock", null); return response.IsSuccessStatusCode; } // ─── Sites ──────────────────────────────────────────────────── public async Task?> GetSitesAsync(int page = 1, int pageSize = 20) { var client = CreateClient(); return await client.GetFromJsonAsync>( $"api/sites?page={page}&pageSize={pageSize}", Json); } public async Task GetSiteAsync(Guid id) { var client = CreateClient(); return await client.GetFromJsonAsync($"api/sites/{id}", Json); } public async Task CreateSiteAsync(string name, string? address, string? timezone) { var client = CreateClient(); var response = await client.PostAsJsonAsync("api/sites", new { name, address, timezone }, Json); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(Json); } public async Task DeleteSiteAsync(Guid id) { var client = CreateClient(); var response = await client.DeleteAsync($"api/sites/{id}"); return response.IsSuccessStatusCode; } public async Task GenerateSiteTokenAsync(Guid siteId) { var client = CreateClient(); var response = await client.PostAsync($"api/sites/{siteId}/tokens", null); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(Json); } // ─── Cameras ──────────────────────────────────────────────────── public async Task?> GetCamerasBySiteAsync(Guid siteId, int page = 1, int pageSize = 20) { var client = CreateClient(); return await client.GetFromJsonAsync>( $"api/cameras/by-site/{siteId}?page={page}&pageSize={pageSize}", Json); } public async Task GetCameraAsync(Guid id) { var client = CreateClient(); return await client.GetFromJsonAsync($"api/cameras/{id}", Json); } public async Task UpdateCameraAsync(Guid id, string name, string? rtspUrl, string? status) { var client = CreateClient(); var response = await client.PutAsJsonAsync($"api/cameras/{id}", new { name, rtspUrl, status }, Json); return response.IsSuccessStatusCode; } public async Task CreateCameraAsync(Guid siteId, string name, string? rtspUrl, string? manufacturer, string? model) { var client = CreateClient(); var response = await client.PostAsJsonAsync("api/cameras", new { siteId, name, rtspUrl, manufacturer, model }, Json); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(Json); } // ─── Stats ──────────────────────────────────────────────────── // ─── Audit Logs ────────────────────────────────────────────── public async Task?> GetAuditLogsAsync( string? resourceType = null, string? action = null, int page = 1, int pageSize = 20) { var client = CreateClient(); var query = $"api/audit-logs?page={page}&pageSize={pageSize}"; if (!string.IsNullOrEmpty(resourceType)) query += $"&resourceType={resourceType}"; if (!string.IsNullOrEmpty(action)) query += $"&action={action}"; return await client.GetFromJsonAsync>(query, Json); } public async Task GetStatsAsync() { var client = CreateClient(); return await client.GetFromJsonAsync("api/stats", Json); } public async Task DeleteCameraAsync(Guid id) { var client = CreateClient(); var response = await client.DeleteAsync($"api/cameras/{id}"); return response.IsSuccessStatusCode; } // ─── Agents ─────────────────────────────────────────────────── public async Task GetAgentAsync(Guid id) { var client = CreateClient(); return await client.GetFromJsonAsync($"api/agents/{id}", Json); } public async Task?> GetAgentsBySiteAsync(Guid siteId, int page = 1, int pageSize = 20) { var client = CreateClient(); return await client.GetFromJsonAsync>( $"api/agents/by-site/{siteId}?page={page}&pageSize={pageSize}", Json); } // ─── Settings ────────────────────────────────────────────────── public async Task> GetSettingsAsync() { var client = CreateClient(); return await client.GetFromJsonAsync>("api/settings") ?? []; } public async Task CreateSettingAsync(CreateAppSettingRequest request) { var client = CreateClient(); return await client.PostAsJsonAsync("api/settings", request); } public async Task UpdateSettingAsync(string key, UpdateAppSettingRequest request) { var client = CreateClient(); return await client.PutAsJsonAsync($"api/settings/{key}", request); } public async Task DeleteSettingAsync(string key) { var client = CreateClient(); return await client.DeleteAsync($"api/settings/{key}"); } public async Task ReloadAllConfigAsync() { var client = CreateClient(); return await client.PostAsync("api/settings/reload", null); } } public class CameraItem { public Guid Id { get; set; } public Guid SiteId { get; set; } public string Name { get; set; } = ""; public string? Manufacturer { get; set; } public string? Model { get; set; } public string? RtspUrl { get; set; } public string Status { get; set; } = "Unknown"; public DateTime CreatedAt { get; set; } } public record TokenResult(string Token, DateTime ExpiresAt); public record StatsResult( int TotalSites, int TotalCameras, int TotalAgents, int OnlineAgents, int ActiveSites); public class AuditLogItem { public Guid Id { get; set; } public Guid? UserId { get; set; } public string? UserEmail { get; set; } public string Action { get; set; } = ""; public string ResourceType { get; set; } = ""; public string? ResourceId { get; set; } public string? OldValue { get; set; } public string? NewValue { get; set; } public string? IpAddress { get; set; } public DateTime Timestamp { get; set; } } public class AgentItem { public Guid Id { get; set; } public Guid SiteId { get; set; } public string Name { get; set; } = ""; public string Hostname { get; set; } = ""; public string Version { get; set; } = ""; public string Status { get; set; } = "Offline"; public DateTime? LastHeartbeat { get; set; } public string? PublicIp { get; set; } public bool HasGpu { get; set; } public int CpuCores { get; set; } public long MemoryMb { get; set; } public string GpuType { get; set; } = "None"; public DateTime CreatedAt { get; set; } } // ─── Settings DTOs ──────────────────────────────────────────────── public record AppSettingItem( [property: JsonPropertyName("id")] Guid Id, [property: JsonPropertyName("key")] string Key, [property: JsonPropertyName("value")] string Value, [property: JsonPropertyName("description")] string? Description, [property: JsonPropertyName("category")] string Category, [property: JsonPropertyName("valueType")] string ValueType, [property: JsonPropertyName("allowedValues")] string? AllowedValues, [property: JsonPropertyName("updatedAt")] DateTime UpdatedAt ); public record CreateAppSettingRequest( [property: JsonPropertyName("key")] string Key, [property: JsonPropertyName("value")] string Value, [property: JsonPropertyName("category")] string Category = "General", [property: JsonPropertyName("description")] string? Description = null, [property: JsonPropertyName("valueType")] string ValueType = "string", [property: JsonPropertyName("allowedValues")] string? AllowedValues = null ); public record UpdateAppSettingRequest( [property: JsonPropertyName("value")] string Value, [property: JsonPropertyName("description")] string? Description = null, [property: JsonPropertyName("category")] string? Category = null, [property: JsonPropertyName("valueType")] string? ValueType = null, [property: JsonPropertyName("allowedValues")] string? AllowedValues = null );