using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; using Heimdall.Application.DTOs; namespace Heimdall.Web.Services; public class HeimdallApiClient : IDisposable { private readonly IHttpClientFactory _httpFactory; private readonly AuthState _authState; private readonly HttpClient? _sessionClient; private const string InvalidServerResponse = "Réponse du serveur invalide."; private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; public HeimdallApiClient(IHttpClientFactory httpFactory, AuthState authState, TokenRefreshHandler? sessionHandler = null) { _httpFactory = httpFactory; _authState = authState; if (sessionHandler is not null) { using var configured = httpFactory.CreateClient("HeimdallApi"); _sessionClient = new HttpClient(sessionHandler, disposeHandler: false) { BaseAddress = configured.BaseAddress, Timeout = configured.Timeout }; } } public void Dispose() { _sessionClient?.Dispose(); GC.SuppressFinalize(this); } private HttpClient CreateClient() { var client = _sessionClient ?? _httpFactory.CreateClient("HeimdallApi"); client.DefaultRequestHeaders.Authorization = string.IsNullOrEmpty(_authState.AccessToken) ? null : new AuthenticationHeaderValue("Bearer", _authState.AccessToken); return client; } /// /// Lit le message d'erreur renvoyé par l'API pour une réponse non-2xx. /// Gère le format maison des controllers ({ error = "..." }) et les /// ProblemDetails / ValidationProblemDetails produits par l'auto-validation /// FluentValidation. Fallback : statut HTTP. /// private static async Task ReadErrorMessageAsync(HttpResponseMessage response) { try { var json = await response.Content.ReadFromJsonAsync(Json); if (json.ValueKind != JsonValueKind.Object) return FallbackErrorMessage(response); // Format maison des controllers : { error = "..." } var error = FindStringProperty(json, "error"); if (!string.IsNullOrWhiteSpace(error)) return error; // ValidationProblemDetails (auto-validation FluentValidation) : { errors = { field: [msg] } } var validationMessages = ExtractValidationMessages(json); if (validationMessages.Length > 0) return string.Join(" ", validationMessages); // ProblemDetails générique : title / detail var title = FindStringProperty(json, "title"); if (!string.IsNullOrWhiteSpace(title)) return title; var detail = FindStringProperty(json, "detail"); if (!string.IsNullOrWhiteSpace(detail)) return detail; } catch { // Corps non-JSON (reverse proxy, etc.) → fallback HTTP } return FallbackErrorMessage(response); } private static string[] ExtractValidationMessages(JsonElement json) { var errors = json.EnumerateObject() .FirstOrDefault(p => string.Equals(p.Name, "errors", StringComparison.OrdinalIgnoreCase) && p.Value.ValueKind == JsonValueKind.Object); if (errors.Value.ValueKind != JsonValueKind.Object) return Array.Empty(); return errors.Value.EnumerateObject() .Where(field => field.Value.ValueKind == JsonValueKind.Array) .SelectMany(field => field.Value.EnumerateArray() .Where(item => item.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(item.GetString())) .Select(item => item.GetString()!)) .ToArray(); } private static string FallbackErrorMessage(HttpResponseMessage response) => $"Erreur du serveur (HTTP {(int)response.StatusCode})"; private static string? FindStringProperty(JsonElement obj, string name) => obj.EnumerateObject() .Where(prop => string.Equals(prop.Name, name, StringComparison.OrdinalIgnoreCase) && prop.Value.ValueKind == JsonValueKind.String) .Select(prop => prop.Value.GetString()) .FirstOrDefault(); // ─── Profile ────────────────────────────────────────────────── public async Task GetMyProfileAsync() { var client = CreateClient(); return await client.GetFromJsonAsync("api/users/me", Json); } public async Task UpdateMyProfileAsync(string displayName, string? theme, string? language) { var client = CreateClient(); var response = await client.PutAsJsonAsync("api/users/me", new { displayName, theme, language }, Json); return response.IsSuccessStatusCode; } public async Task ChangePasswordAsync(string currentPassword, string newPassword) { var client = CreateClient(); var response = await client.PostAsJsonAsync("api/auth/change-password", new { currentPassword, newPassword }, Json); return response.IsSuccessStatusCode; } // ─── Roles ──────────────────────────────────────────────────── public async Task> GetRolesAsync() { var client = CreateClient(); var response = await client.GetFromJsonAsync("api/roles", Json); return response?.Roles.ToList() ?? []; } // ─── Permissions ────────────────────────────────────────────── public async Task> GetPermissionsAsync() { var client = CreateClient(); var response = await client.GetFromJsonAsync("api/permissions", Json); return response?.Permissions.ToList() ?? []; } // ─── Groups ─────────────────────────────────────────────────── public async Task?> GetGroupsAsync(int page = 1, int pageSize = 20) { var client = CreateClient(); return await client.GetFromJsonAsync>( $"api/groups?page={page}&pageSize={pageSize}", Json); } public async Task GetGroupAsync(Guid id) { var client = CreateClient(); return await client.GetFromJsonAsync($"api/groups/{id}", Json); } public async Task CreateGroupAsync(string name, string? description) { var client = CreateClient(); var response = await client.PostAsJsonAsync("api/groups", new { name, description }, Json); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(Json); } public async Task UpdateGroupAsync(Guid id, string name, string? description) { var client = CreateClient(); var response = await client.PutAsJsonAsync($"api/groups/{id}", new { name, description }, Json); return response.IsSuccessStatusCode; } public async Task DeleteGroupAsync(Guid id) { var client = CreateClient(); var response = await client.DeleteAsync($"api/groups/{id}"); return response.IsSuccessStatusCode; } public async Task AddUserToGroupAsync(Guid groupId, Guid userId) { var client = CreateClient(); var response = await client.PostAsJsonAsync($"api/groups/{groupId}/users", new { userId }, Json); return response.IsSuccessStatusCode; } public async Task RemoveUserFromGroupAsync(Guid groupId, Guid userId) { var client = CreateClient(); var response = await client.DeleteAsync($"api/groups/{groupId}/users/{userId}"); return response.IsSuccessStatusCode; } // ─── 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; var result = await response.Content.ReadFromJsonAsync(Json); if (result is not null) _lastAuthResponse = result; return result; } 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; var result = await response.Content.ReadFromJsonAsync(Json); if (result is not null) _lastAuthResponse = result; return result; } public async Task Verify2faAsync(string challengeId, string code) { var client = CreateClient(); var response = await client.PostAsJsonAsync("api/auth/2fa/verify", new { challengeId, code }); if (!response.IsSuccessStatusCode) return null; var result = await response.Content.ReadFromJsonAsync(Json); if (result is not null) _lastAuthResponse = result; return result; } public async Task Enable2faAsync() { var client = CreateClient(); var response = await client.PostAsync("api/auth/2fa/enable", null); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(Json); } public async Task Disable2faAsync() { var client = CreateClient(); var response = await client.PostAsync("api/auth/2fa/disable", null); return response.IsSuccessStatusCode; } /// /// Stores the last successful auth response for use by the token refresh handler. /// internal AuthResponse? _lastAuthResponse; // ─── 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> UpdateUserWithEmailAsync( Guid id, string email, string displayName, string? theme, string? language) { var client = CreateClient(); var response = await client.PutAsJsonAsync($"api/users/{id}", new { email, displayName, theme, language }, Json); if (!response.IsSuccessStatusCode) return ApiResult.Failure(await ReadErrorMessageAsync(response)); var user = await response.Content.ReadFromJsonAsync(Json); return user is null ? ApiResult.Failure(InvalidServerResponse) : ApiResult.Success(user); } 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; } public async Task ConfirmUserEmailAsync(Guid userId) { var client = CreateClient(); var response = await client.PostAsync($"api/users/{userId}/confirm-email", null); return response.IsSuccessStatusCode; } /// /// Supprime un utilisateur par son identifiant. /// /// null en cas de succès, sinon le message d'erreur du serveur. public async Task DeleteUserAsync(Guid id) { var client = CreateClient(); var response = await client.DeleteAsync($"api/users/{id}"); if (response.IsSuccessStatusCode) return null; return await ReadErrorMessageAsync(response); } // ─── 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, string? ntfyTopic = null) { var client = CreateClient(); var response = await client.PostAsJsonAsync("api/sites", new { name, address, timezone, ntfyTopic }, Json); if (!response.IsSuccessStatusCode) return ApiResult.Failure(await ReadErrorMessageAsync(response)); var site = await response.Content.ReadFromJsonAsync(Json); return site is null ? ApiResult.Failure(InvalidServerResponse) : ApiResult.Success(site); } public async Task UpdateSiteAsync(Guid id, string name, string? address, string? timezone, string? ntfyTopic = null, bool? autoUpdateEnabled = null) { var client = CreateClient(); var response = await client.PutAsJsonAsync($"api/sites/{id}", new { name, address, timezone, ntfyTopic, autoUpdateEnabled }, Json); return response.IsSuccessStatusCode; } public async Task GetSiteCascadeInfoAsync(Guid siteId) { var client = CreateClient(); var response = await client.GetAsync($"api/sites/{siteId}/cascade-info"); 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, string? manufacturer = null, string? model = null) { var client = CreateClient(); var response = await client.PutAsJsonAsync($"api/cameras/{id}", new { name, rtspUrl, status, manufacturer, model }, Json); return response.IsSuccessStatusCode; } public async Task> ToggleCameraStatusAsync(Guid id) { var client = CreateClient(); var response = await client.PostAsync($"api/cameras/{id}/toggle-status", null); if (!response.IsSuccessStatusCode) return ApiResult.Failure(await ReadErrorMessageAsync(response)); var camera = await response.Content.ReadFromJsonAsync(Json); return camera is null ? ApiResult.Failure(InvalidServerResponse) : ApiResult.Success(camera); } 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 ApiResult.Failure(await ReadErrorMessageAsync(response)); var camera = await response.Content.ReadFromJsonAsync(Json); return camera is null ? ApiResult.Failure(InvalidServerResponse) : ApiResult.Success(camera); } // ─── Site camera credentials ─────────────────────────────────── public async Task> GetSiteCredentialsAsync(Guid siteId) { var client = CreateClient(); return await client.GetFromJsonAsync>( $"api/sites/{siteId}/credentials", Json) ?? []; } public async Task AddSiteCredentialAsync(Guid siteId, string label, string username, string password) { var client = CreateClient(); var response = await client.PostAsJsonAsync($"api/sites/{siteId}/credentials", new { label, username, password }, Json); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(Json); } public async Task DeleteSiteCredentialAsync(Guid siteId, Guid credentialId) { var client = CreateClient(); var response = await client.DeleteAsync($"api/sites/{siteId}/credentials/{credentialId}"); return response.IsSuccessStatusCode; } // ─── Camera discovery (agent-submitted) ────────────────────────── public async Task> GetPendingDiscoveriesAsync(Guid siteId) { var client = CreateClient(); return await client.GetFromJsonAsync>( $"api/discovery/sites/{siteId}", Json) ?? []; } public async Task ScanNowAsync(Guid siteId) { var client = CreateClient(); var response = await client.PostAsync($"api/discovery/sites/{siteId}/scan-now", null); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(Json); } public async Task RejectDiscoveryAsync(Guid resultId) { var client = CreateClient(); var response = await client.PostAsync($"api/discovery/{resultId}/reject", null); return response.IsSuccessStatusCode; } public async Task> ConfirmDiscoveryAsync( Guid siteId, Guid discoveryResultId, string name, string mainStreamUrl, string? username, string? password, Guid? agentId = null) { var client = CreateClient(); var response = await client.PostAsJsonAsync("api/discovery/confirm", new { siteId, discoveryResultId, name, mainStreamUrl, username, password, agentId }, Json); if (!response.IsSuccessStatusCode) return ApiResult.Failure(await ReadErrorMessageAsync(response)); var camera = await response.Content.ReadFromJsonAsync(Json); return camera is null ? ApiResult.Failure(InvalidServerResponse) : ApiResult.Success(camera); } // ─── Stats ──────────────────────────────────────────────────── // ─── Audit Logs ────────────────────────────────────────────── public async Task?> GetAuditLogsAsync( string? resourceType = null, string? action = null, int page = 1, int pageSize = 20, string? search = null, string? userId = null, DateTime? fromDate = null, DateTime? toDate = null) { var client = CreateClient(); var query = $"api/audit-logs?page={page}&pageSize={pageSize}"; if (!string.IsNullOrEmpty(resourceType)) query += $"&resourceType={Uri.EscapeDataString(resourceType)}"; if (!string.IsNullOrEmpty(action)) query += $"&action={Uri.EscapeDataString(action)}"; if (!string.IsNullOrEmpty(search)) query += $"&search={Uri.EscapeDataString(search)}"; if (!string.IsNullOrEmpty(userId)) query += $"&userId={userId}"; if (fromDate.HasValue) query += $"&fromDate={Uri.EscapeDataString(fromDate.Value.ToString("O", System.Globalization.CultureInfo.InvariantCulture))}"; if (toDate.HasValue) query += $"&toDate={Uri.EscapeDataString(toDate.Value.ToString("O", System.Globalization.CultureInfo.InvariantCulture))}"; return await client.GetFromJsonAsync>(query, Json); } public async Task?> GetAgentLogsAsync( Guid agentId, string? level = null, string? search = null, int page = 1, int pageSize = 50) { var client = CreateClient(); var query = $"api/agents/{agentId}/logs?page={page}&pageSize={pageSize}"; if (!string.IsNullOrEmpty(level)) query += $"&level={Uri.EscapeDataString(level)}"; if (!string.IsNullOrEmpty(search)) query += $"&search={Uri.EscapeDataString(search)}"; return await client.GetFromJsonAsync>(query, Json); } public async Task GetStatsAsync() { var client = CreateClient(); // The API wraps the payload: { "data": { ... }, "timestamp": ... } var envelope = await client.GetFromJsonAsync("api/stats", Json); return envelope?.Data; } 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); } /// List all agents across all sites (admin). public async Task?> GetAllAgentsAsync(int page = 1, int pageSize = 20) { var client = CreateClient(); return await client.GetFromJsonAsync>( $"api/agents?page={page}&pageSize={pageSize}", Json); } /// /// Supprime un agent par son identifiant (soft-delete + désassignation des caméras). /// /// null en cas de succès, sinon le message d'erreur du serveur. public async Task DeleteAgentAsync(Guid id) { var client = CreateClient(); var response = await client.DeleteAsync($"api/agents/{id}"); if (response.IsSuccessStatusCode) return null; return await ReadErrorMessageAsync(response); } /// Get agent-specific KPIs for the dashboard. public async Task> GetAgentStatsAsync() { var client = CreateClient(); return await client.GetFromJsonAsync>("api/stats/agent-stats") ?? []; } // ─── Updates ───────────────────────────────────────────────── public async Task GetLatestUpdateAsync() { var client = CreateClient(); return await client.GetFromJsonAsync("api/updates/latest", Json); } public async Task TriggerAgentUpdateAsync(Guid agentId) { var client = CreateClient(); var response = await client.PostAsync($"api/updates/agents/{agentId}/update", null); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(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}"); } /// Test the active storage provider reachability (POST /api/settings/storage/test). public async Task TestStorageAsync() { var client = CreateClient(); var response = await client.PostAsync("api/settings/storage/test", null); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(); } /// Send a test email (POST /api/settings/email/test). public async Task TestEmailAsync() { var client = CreateClient(); var response = await client.PostAsync("api/settings/email/test", null); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(); } /// Send a test ntfy notification (POST /api/settings/ntfy/test). public async Task TestNtfyAsync(string? topic = null, string? baseUrl = null) { var client = CreateClient(); var payload = new { topic, baseUrl }; var response = await client.PostAsJsonAsync("api/settings/ntfy/test", payload, Json); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(); } /// Ping the AI backends (POST /api/settings/ai/test). public async Task TestAiAsync() { var client = CreateClient(); var response = await client.PostAsync("api/settings/ai/test", null); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(); } public async Task ReloadAllConfigAsync() { var client = CreateClient(); return await client.PostAsync("api/settings/reload", null); } // ─── Agent Settings Overrides ─────────────────────────────────── public async Task> GetAgentSettingsAsync(Guid agentId) { var client = CreateClient(); return await client.GetFromJsonAsync>( $"api/settings/agent/{agentId}/overrides") ?? []; } public async Task SetAgentSettingAsync(Guid agentId, SetAgentSettingRequest request) { var client = CreateClient(); return await client.PutAsJsonAsync($"api/settings/agent/{agentId}/overrides", request); } public async Task RemoveAgentSettingAsync(Guid agentId, string key) { var client = CreateClient(); return await client.DeleteAsync($"api/settings/agent/{agentId}/overrides/{key}"); } public async Task> GetEffectiveAgentConfigAsync(Guid agentId) { var client = CreateClient(); return await client.GetFromJsonAsync>( $"api/settings/agent/{agentId}") ?? []; } // ─── API Keys ─────────────────────────────────────────────────── public async Task> GetApiKeysAsync() { var client = CreateClient(); return await client.GetFromJsonAsync>("api/api-keys", Json) ?? []; } public async Task CreateApiKeyAsync(Guid? siteId, DateTime? expiresAt) { var client = CreateClient(); var response = await client.PostAsJsonAsync("api/api-keys", new { siteId, expiresAt }, Json); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(Json); } public async Task RevokeApiKeyAsync(Guid id) { var client = CreateClient(); var response = await client.DeleteAsync($"api/api-keys/{id}"); return response.IsSuccessStatusCode; } // ─── Persons ────────────────────────────────────────────────────── public async Task?> GetPersonsAsync(string? category = null) { var client = CreateClient(); var url = string.IsNullOrEmpty(category) ? "api/persons" : $"api/persons?category={Uri.EscapeDataString(category)}"; return await client.GetFromJsonAsync>(url, Json); } public async Task GetPersonAsync(Guid id) { var client = CreateClient(); return await client.GetFromJsonAsync($"api/persons/{id}", Json); } public async Task> CreatePersonAsync( string displayName, string? category, string? notes, bool isWatchlisted, string? photoUrl = null) { var client = CreateClient(); var response = await client.PostAsJsonAsync("api/persons", new { displayName, category, notes, isWatchlisted, photoUrl }, Json); if (!response.IsSuccessStatusCode) return ApiResult.Failure(await ReadErrorMessageAsync(response)); var person = await response.Content.ReadFromJsonAsync(Json); return person is null ? ApiResult.Failure(InvalidServerResponse) : ApiResult.Success(person); } public async Task UpdatePersonAsync(PersonClientItem person) { var client = CreateClient(); var response = await client.PutAsJsonAsync($"api/persons/{person.Id}", new { person.DisplayName, person.Notes, person.Category, person.IsWatchlisted, person.PhotoUrl }, Json); return response.IsSuccessStatusCode; } public async Task DeletePersonAsync(Guid id) { var client = CreateClient(); var response = await client.DeleteAsync($"api/persons/{id}"); return response.IsSuccessStatusCode; } // ─── Faces ──────────────────────────────────────────────────────── public async Task?> GetFacesAsync(Guid personId) { var client = CreateClient(); return await client.GetFromJsonAsync>( $"api/persons/{personId}/faces", Json); } public async Task> RegisterFaceAsync( Guid personId, float[] embedding, string? thumbnailUrl = null, string? sourceEventId = null) { var client = CreateClient(); var response = await client.PostAsJsonAsync($"api/persons/{personId}/faces", new { embedding, thumbnailUrl, sourceEventId }, Json); if (!response.IsSuccessStatusCode) return ApiResult.Failure(await ReadErrorMessageAsync(response)); var face = await response.Content.ReadFromJsonAsync(Json); return face is null ? ApiResult.Failure(InvalidServerResponse) : ApiResult.Success(face); } public async Task DeleteFaceAsync(Guid faceId) { var client = CreateClient(); var response = await client.DeleteAsync($"api/persons/faces/{faceId}"); return response.IsSuccessStatusCode; } // ─── Vehicles (filtered client-side by PersonId) ────────────────── public async Task?> GetVehiclesAsync() { var client = CreateClient(); return await client.GetFromJsonAsync>("api/vehicles", Json); } // ─── Events ──────────────────────────────────────────────────────── public async Task GetEventsAsync(Guid? cameraId, Guid? siteId, int page = 1, int pageSize = 50, string? q = null, string? type = null, DateTime? from = null, DateTime? to = null, bool hasSnapshot = false) { var client = CreateClient(); var query = $"page={page}&pageSize={pageSize}"; if (cameraId.HasValue) query += $"&cameraId={cameraId}"; if (siteId.HasValue) query += $"&siteId={siteId}"; if (hasSnapshot) query += "&hasSnapshot=true"; if (!string.IsNullOrWhiteSpace(q)) query += $"&q={Uri.EscapeDataString(q)}"; if (!string.IsNullOrWhiteSpace(type)) query += $"&type={Uri.EscapeDataString(type)}"; if (from.HasValue) query += $"&from={Uri.EscapeDataString(from.Value.ToString("O", System.Globalization.CultureInfo.InvariantCulture))}"; if (to.HasValue) query += $"&to={Uri.EscapeDataString(to.Value.ToString("O", System.Globalization.CultureInfo.InvariantCulture))}"; return await client.GetFromJsonAsync($"api/events?{query}", Json); } public async Task?> GetRecentEventsAsync(Guid cameraId, int count = 20) { var client = CreateClient(); return await client.GetFromJsonAsync>($"api/events/camera/{cameraId}?count={count}", Json); } public async Task GetEventAsync(Guid eventId) { var client = CreateClient(); return await client.GetFromJsonAsync($"api/events/{eventId}", Json); } // ─── Notification Config ───────────────────────────────────────── public async Task GetNotificationConfigAsync() { var client = CreateClient(); return await client.GetFromJsonAsync("api/notifications/config", Json); } public async Task UpdateNotificationConfigAsync(UpdateNotificationConfigRequest request) { var client = CreateClient(); var response = await client.PutAsJsonAsync("api/notifications/config", request, Json); return response.IsSuccessStatusCode; } // ─── User Camera Access ────────────────────────────────────────── public async Task?> GetUserCameraAccessAsync(Guid userId, int page = 1, int pageSize = 20) { var client = CreateClient(); return await client.GetFromJsonAsync>( $"api/user-camera-access/user/{userId}?page={page}&pageSize={pageSize}", Json); } public async Task CreateUserCameraAccessAsync(CreateUserCameraAccessRequest request) { var client = CreateClient(); var response = await client.PostAsJsonAsync("api/user-camera-access", request, Json); if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadFromJsonAsync(Json); } public async Task DeleteUserCameraAccessAsync(Guid id) { var client = CreateClient(); var response = await client.DeleteAsync($"api/user-camera-access/{id}"); return response.IsSuccessStatusCode; } } 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; } } /// /// Résultat d'un appel API : succès avec données, ou échec avec le message /// d'erreur renvoyé par le back-end (au lieu de retourner null et d'avaler /// l'erreur — issue #93). /// #pragma warning disable CA1000 // Do not declare static members on generic types public sealed class ApiResult { public bool Succeeded { get; init; } public T? Data { get; init; } public string? ErrorMessage { get; init; } public static ApiResult Success(T data) => new() { Succeeded = true, Data = data }; public static ApiResult Failure(string errorMessage) => new() { Succeeded = false, ErrorMessage = errorMessage }; } #pragma warning restore CA1000 public record TokenResult(string Token, DateTime ExpiresAt); // ─── Site credentials & discovery DTOs ───────────────────────────── public class SiteCredentialItem { public Guid Id { get; set; } public Guid SiteId { get; set; } public string Label { get; set; } = ""; public string Username { get; set; } = ""; public DateTime CreatedAt { get; set; } public DateTime? LastUsedAt { get; set; } } public class PendingDiscoveryItem { public Guid Id { get; set; } public Guid SiteId { get; set; } public string IpAddress { get; set; } = ""; public string? MacAddress { get; set; } public string? Vendor { get; set; } public string? Hostname { get; set; } public bool IsReachable { get; set; } public string DetectedType { get; set; } = ""; public string DiscoveryMethod { get; set; } = ""; public int[] OpenPorts { get; set; } = []; public string? OnvifDeviceServiceUrl { get; set; } public string? OnvifName { get; set; } public string? OnvifHardware { get; set; } public int? OnvifPort { get; set; } public string? HttpServerHeader { get; set; } public int? HttpStatusCode { get; set; } public int? HttpPort { get; set; } public DateTime ProbedAt { get; set; } public bool IsProcessed { get; set; } public string[] StreamUrls { get; set; } = []; public bool HasScreenshot { get; set; } } public record ScanNowResult(int AgentsNotified); public record StatsResult( int TotalSites, int TotalCameras, int TotalAgents, int OnlineAgents, int ActiveSites, int OfflineAgents, int CamerasOnline, int CamerasOffline, int TotalUsers); /// Envelope returned by GET /api/stats: { data: StatsResult, timestamp: ... }. public record StatsEnvelope(StatsResult Data, DateTime Timestamp); public record AgentStatItem(string StatType, string Label, int Value, string Color); 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 string? ResourceName { get; set; } } public class AgentItem { public Guid Id { get; set; } public Guid SiteId { get; set; } public string SiteName { 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 string? GpuName { get; set; } public long? VramMb { get; set; } public double? GpuLoadPercent { get; set; } public long? VramUsageBytes { get; set; } public DateTime CreatedAt { get; set; } public double? CpuUsagePercent { get; set; } public long? MemoryUsageBytes { get; set; } public double? DiskUsagePercent { get; set; } public long? UptimeSeconds { get; set; } // CPU inventory public string? CpuVendor { get; set; } public string? CpuModel { get; set; } public string? CpuArchitecture { get; set; } public int? PhysicalCores { get; set; } public int? LogicalCores { get; set; } public int? ThreadsPerCore { get; set; } public double? CpuFrequencyMhz { get; set; } public string? CpuFlags { get; set; } public long? CpuCacheBytes { get; set; } public long? ContainerCpuLimit { get; set; } // Memory inventory public long? MemTotalBytes { get; set; } public long? MemAvailableBytes { get; set; } public long? SwapTotalBytes { get; set; } public long? SwapFreeBytes { get; set; } public long? ContainerMemoryLimitBytes { get; set; } // Disk inventory public string? DiskInventoryJson { get; set; } // GPU inventory public string? GpuInventoryJson { get; set; } // Host info public string? OsName { get; set; } public string? KernelVersion { get; set; } public string? Arch { get; set; } public long? UptimeMachineSeconds { get; set; } // Container info public string? ContainerId { get; set; } public string? ContainerImage { get; set; } // Network & Temperature public string? NetworkInterfacesJson { get; set; } public string? TemperatureJson { get; set; } } public class AgentLogItem { public Guid Id { get; set; } public Guid AgentId { get; set; } public DateTime TimestampUtc { get; set; } public string Level { get; set; } = ""; public string Message { get; set; } = ""; public string? Exception { get; set; } public string? Source { get; set; } } // ─── Persons & Faces DTOs ────────────────────────────────────────── public class PersonClientItem { [JsonPropertyName("id")] public Guid Id { get; set; } [JsonPropertyName("displayName")] public string DisplayName { get; set; } = ""; [JsonPropertyName("notes")] public string? Notes { get; set; } [JsonPropertyName("photoUrl")] public string? PhotoUrl { get; set; } [JsonPropertyName("category")] public string? Category { get; set; } [JsonPropertyName("isWatchlisted")] public bool IsWatchlisted { get; set; } [JsonPropertyName("faceCount")] public int FaceCount { get; set; } [JsonPropertyName("createdAt")] public DateTime CreatedAt { get; set; } } public class KnownFaceClientItem { [JsonPropertyName("id")] public Guid Id { get; set; } [JsonPropertyName("personId")] public Guid PersonId { get; set; } [JsonPropertyName("thumbnailUrl")] public string? ThumbnailUrl { get; set; } [JsonPropertyName("sourceEventId")] public string? SourceEventId { get; set; } } public class VehicleClientItem { [JsonPropertyName("id")] public Guid Id { get; set; } [JsonPropertyName("licensePlate")] public string? LicensePlate { get; set; } [JsonPropertyName("make")] public string? Make { get; set; } [JsonPropertyName("model")] public string? Model { get; set; } [JsonPropertyName("color")] public string? Color { get; set; } [JsonPropertyName("personId")] public Guid? PersonId { get; set; } [JsonPropertyName("personName")] public string? PersonName { get; set; } [JsonPropertyName("eventCount")] public int EventCount { get; set; } [JsonPropertyName("createdAt")] public DateTime CreatedAt { get; set; } } // ─── Storage DTOs ────────────────────────────────────────────────── public record StorageTestResult( [property: JsonPropertyName("provider")] string Provider, [property: JsonPropertyName("configured")] bool Configured, [property: JsonPropertyName("healthy")] bool? Healthy ); /// Résultat d'un test d'intégration (email / ntfy / IA). public record TestActionResult( [property: JsonPropertyName("success")] bool Success, [property: JsonPropertyName("message")] string? Message, [property: JsonPropertyName("status")] string? Status = null ); // ─── 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, [property: JsonPropertyName("agentScoped")] bool AgentScoped = true ); 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, [property: JsonPropertyName("agentScoped")] bool AgentScoped = true ); 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, [property: JsonPropertyName("agentScoped")] bool? AgentScoped = null ); // ─── Agent Settings DTOs ─────────────────────────────────────────── public record AgentSettingItem( [property: JsonPropertyName("id")] Guid Id, [property: JsonPropertyName("agentId")] Guid AgentId, [property: JsonPropertyName("key")] string Key, [property: JsonPropertyName("value")] string Value, [property: JsonPropertyName("updatedAt")] DateTime UpdatedAt ); public record SetAgentSettingRequest( [property: JsonPropertyName("key")] string Key, [property: JsonPropertyName("value")] string Value ); public record EventItem( [property: JsonPropertyName("id")] Guid Id, [property: JsonPropertyName("cameraId")] Guid CameraId, [property: JsonPropertyName("type")] string Type, [property: JsonPropertyName("confidence")] double Confidence, [property: JsonPropertyName("label")] string? Label, [property: JsonPropertyName("snapshotUrl")] string? SnapshotUrl, [property: JsonPropertyName("snapshotThumbUrl")] string? SnapshotThumbUrl, [property: JsonPropertyName("occurredAt")] DateTime OccurredAt, [property: JsonPropertyName("createdAt")] DateTime CreatedAt); public record EventPageResult( [property: JsonPropertyName("items")] List Items, [property: JsonPropertyName("totalCount")] int TotalCount, [property: JsonPropertyName("page")] int Page, [property: JsonPropertyName("pageSize")] int PageSize); // ─── Roles & Permissions DTOs ────────────────────────────────────── public record RoleItem( [property: JsonPropertyName("name")] string Name, [property: JsonPropertyName("permissions")] IReadOnlyList Permissions); public record RolesListResponse( [property: JsonPropertyName("roles")] IReadOnlyList Roles); public record PermissionItem( [property: JsonPropertyName("name")] string Name, [property: JsonPropertyName("displayName")] string DisplayName, [property: JsonPropertyName("category")] string Category); public record PermissionsListResponse( [property: JsonPropertyName("permissions")] IReadOnlyList Permissions); // ─── Group DTOs ──────────────────────────────────────────────────── public class GroupItem { public Guid Id { get; set; } public string Name { get; set; } = ""; public string? Description { get; set; } public DateTime CreatedAt { get; set; } public int MemberCount { get; set; } } // ─── Notification Config DTOs ───────────────────────────────────────── public class NotificationConfigItem { public Guid Id { get; set; } public Guid UserId { get; set; } public bool EmailEnabled { get; set; } public string? EmailAddress { get; set; } public bool NtfyEnabled { get; set; } public string? NtfyUrl { get; set; } public string? NtfyTopic { get; set; } public string Language { get; set; } = "fr"; public bool DailyDigest { get; set; } public bool WeeklyDigest { get; set; } public List? SubscribedEvents { get; set; } } public record UpdateNotificationConfigRequest( bool? EmailEnabled, string? EmailAddress, bool? NtfyEnabled, string? NtfyUrl, string? NtfyTopic, bool? DailyDigest, bool? WeeklyDigest, List? SubscribedEvents ); // ─── API Key DTOs ────────────────────────────────────────────────── public record ApiKeyListItem( [property: JsonPropertyName("id")] Guid Id, [property: JsonPropertyName("keyPrefix")] string KeyPrefix, [property: JsonPropertyName("siteId")] Guid? SiteId, [property: JsonPropertyName("siteName")] string? SiteName, [property: JsonPropertyName("createdAt")] DateTime CreatedAt, [property: JsonPropertyName("expiresAt")] DateTime? ExpiresAt, [property: JsonPropertyName("enabled")] bool Enabled, [property: JsonPropertyName("lastUsedAt")] DateTime? LastUsedAt); public record CreateApiKeyResult( [property: JsonPropertyName("id")] Guid Id, [property: JsonPropertyName("plainKey")] string PlainKey, [property: JsonPropertyName("keyPrefix")] string KeyPrefix, [property: JsonPropertyName("siteId")] Guid? SiteId, [property: JsonPropertyName("expiresAt")] DateTime? ExpiresAt); public class LatestReleaseInfo { [JsonPropertyName("version")] public string Version { get; set; } = ""; [JsonPropertyName("releaseNotes")] public string? ReleaseNotes { get; set; } [JsonPropertyName("publishedAt")] public DateTime? PublishedAt { get; set; } [JsonPropertyName("assets")] public Dictionary Assets { get; set; } = []; [JsonPropertyName("containerImage")] public string? ContainerImage { get; set; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; } } public class PlatformAssetInfo { [JsonPropertyName("url")] public string Url { get; set; } = ""; [JsonPropertyName("sha256")] public string? Sha256 { get; set; } [JsonPropertyName("size")] public long Size { get; set; } } public record SiteCascadeInfo([property: JsonPropertyName("agentCount")] int AgentCount, [property: JsonPropertyName("cameraCount")] int CameraCount); // ─── User Camera Access DTOs ──────────────────────────────────────── public record UserCameraAccessResponse( [property: JsonPropertyName("id")] Guid Id, [property: JsonPropertyName("userId")] Guid UserId, [property: JsonPropertyName("siteId")] Guid SiteId, [property: JsonPropertyName("cameraId")] Guid? CameraId, [property: JsonPropertyName("grantedAt")] DateTime GrantedAt); public record CreateUserCameraAccessRequest( [property: JsonPropertyName("userId")] Guid UserId, [property: JsonPropertyName("siteId")] Guid SiteId, [property: JsonPropertyName("cameraId")] Guid? CameraId); public record ApiResultUserCameraAccessResponse( [property: JsonPropertyName("id")] Guid Id, [property: JsonPropertyName("userId")] Guid UserId, [property: JsonPropertyName("siteId")] Guid SiteId, [property: JsonPropertyName("cameraId")] Guid? CameraId, [property: JsonPropertyName("grantedAt")] DateTime GrantedAt);