Files
Heimdall/src/Heimdall.Web/Services/HeimdallApiClient.cs
T
arnaud.dartois 2bf3dbc95b
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Successful in 20m8s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Failing after 6m10s
Heimdall Gitea / Build and scan server image (pull_request) Failing after 8m2s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 2s
fix(identity): harden user lifecycle and permissions
2026-11-04 10:26:07 +01:00

1463 lines
64 KiB
C#

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;
}
/// <summary>
/// Lit le message d'erreur renvoyé par l'API pour une réponse non-2xx.
/// Gère le format maison des controllers (<c>{ error = "..." }</c>) et les
/// ProblemDetails / ValidationProblemDetails produits par l'auto-validation
/// FluentValidation. Fallback : statut HTTP.
/// </summary>
private static async Task<string> ReadErrorMessageAsync(HttpResponseMessage response)
{
try
{
var json = await response.Content.ReadFromJsonAsync<JsonElement>(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<string>();
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<UserItem?> GetMyProfileAsync()
{
var client = CreateClient();
return await client.GetFromJsonAsync<UserItem>("api/users/me", Json);
}
public async Task<int> GetUnreadNotificationCountAsync()
{
using var response = await CreateClient().GetAsync("api/notifications/unread-count");
if (!response.IsSuccessStatusCode)
return 0;
var result = await response.Content.ReadFromJsonAsync<Heimdall.Application.DTOs.UnreadCountDto>(Json);
return result?.Count ?? 0;
}
public async Task<bool> 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<bool> 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<List<RoleItem>> GetRolesAsync()
{
var client = CreateClient();
var response = await client.GetFromJsonAsync<RolesListResponse>("api/roles", Json);
return response?.Roles.ToList() ?? [];
}
public async Task<bool> UpdateRolePermissionsAsync(string role, IReadOnlyList<string> permissions)
{
var client = CreateClient();
var response = await client.PutAsJsonAsync($"api/roles/{Uri.EscapeDataString(role)}/permissions",
new { permissions }, Json);
return response.IsSuccessStatusCode;
}
// ─── Permissions ──────────────────────────────────────────────
public async Task<List<PermissionItem>> GetPermissionsAsync()
{
var client = CreateClient();
var response = await client.GetFromJsonAsync<PermissionsListResponse>("api/permissions", Json);
return response?.Permissions.ToList() ?? [];
}
// ─── Groups ───────────────────────────────────────────────────
public async Task<PagedData<GroupItem>?> GetGroupsAsync(int page = 1, int pageSize = 20)
{
var client = CreateClient();
return await client.GetFromJsonAsync<PagedData<GroupItem>>(
$"api/groups?page={page}&pageSize={pageSize}", Json);
}
public async Task<GroupItem?> GetGroupAsync(Guid id)
{
var client = CreateClient();
return await client.GetFromJsonAsync<GroupItem>($"api/groups/{id}", Json);
}
public async Task<GroupItem?> 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<GroupItem>(Json);
}
public async Task<bool> 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<bool> DeleteGroupAsync(Guid id)
{
var client = CreateClient();
var response = await client.DeleteAsync($"api/groups/{id}");
return response.IsSuccessStatusCode;
}
public async Task<bool> 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<bool> RemoveUserFromGroupAsync(Guid groupId, Guid userId)
{
var client = CreateClient();
var response = await client.DeleteAsync($"api/groups/{groupId}/users/{userId}");
return response.IsSuccessStatusCode;
}
public async Task<PagedData<CameraItem>?> GetGroupCamerasAsync(Guid groupId, int page = 1, int pageSize = 20)
{
var client = CreateClient();
return await client.GetFromJsonAsync<PagedData<CameraItem>>(
$"api/groups/{groupId}/cameras?page={page}&pageSize={pageSize}", Json);
}
public async Task<bool> AddCameraToGroupAsync(Guid groupId, Guid cameraId)
{
var client = CreateClient();
var response = await client.PostAsJsonAsync($"api/groups/{groupId}/cameras",
new { groupId, cameraId }, Json);
return response.IsSuccessStatusCode;
}
public async Task<bool> RemoveCameraFromGroupAsync(Guid groupId, Guid cameraId)
{
var client = CreateClient();
var response = await client.DeleteAsync($"api/groups/{groupId}/cameras/{cameraId}");
return response.IsSuccessStatusCode;
}
// ─── Auth ─────────────────────────────────────────────────────
public async Task<AuthResponse?> 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<AuthResponse>(Json);
if (result is not null) _lastAuthResponse = result;
return result;
}
public async Task<bool> IsAdminSetupRequiredAsync()
{
var client = CreateClient();
var result = await client.GetFromJsonAsync<BootstrapStatus>("api/auth/bootstrap-status", Json);
return result?.SetupRequired ?? throw new InvalidOperationException("Invalid bootstrap status response.");
}
public async Task<AuthResponse?> BootstrapAdminAsync(string email, string password, string displayName)
{
var client = CreateClient();
var response = await client.PostAsJsonAsync("api/auth/bootstrap-admin",
new { email, password, displayName });
if (!response.IsSuccessStatusCode) return null;
var result = await response.Content.ReadFromJsonAsync<AuthResponse>(Json);
if (result is not null) _lastAuthResponse = result;
return result;
}
private sealed record BootstrapStatus(bool SetupRequired);
public async Task<AuthResponse?> 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<AuthResponse>(Json);
if (result is not null) _lastAuthResponse = result;
return result;
}
public async Task<Enable2faResponse?> Enable2faAsync(string currentPassword)
{
var client = CreateClient();
var response = await client.PostAsJsonAsync("api/auth/2fa/enable", new Enable2faRequest(currentPassword));
if (!response.IsSuccessStatusCode) return null;
return await response.Content.ReadFromJsonAsync<Enable2faResponse>(Json);
}
public async Task<Complete2faSetupResponse?> ConfirmEnable2faAsync(string code)
{
var client = CreateClient();
var response = await client.PostAsJsonAsync("api/auth/2fa/enable/confirm", new Complete2faSetupRequest(code));
if (!response.IsSuccessStatusCode) return null;
return await response.Content.ReadFromJsonAsync<Complete2faSetupResponse>(Json);
}
public async Task<bool> Disable2faAsync(string currentPassword)
{
var client = CreateClient();
var response = await client.PostAsJsonAsync("api/auth/2fa/disable", new Disable2faRequest(currentPassword));
return response.IsSuccessStatusCode;
}
/// <summary>
/// Stores the last successful auth response for use by the token refresh handler.
/// </summary>
internal AuthResponse? _lastAuthResponse;
// ─── Users ────────────────────────────────────────────────────
public async Task<PagedData<UserItem>?> GetUsersAsync(int page = 1, int pageSize = 20)
{
var client = CreateClient();
return await client.GetFromJsonAsync<PagedData<UserItem>>(
$"api/users?page={page}&pageSize={pageSize}", Json);
}
public async Task<UserItem?> GetUserAsync(Guid id)
{
var client = CreateClient();
return await client.GetFromJsonAsync<UserItem>($"api/users/{id}", Json);
}
public async Task<UserItem?> CreateUserAsync(string email, string password, string displayName, IList<string> 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<UserItem>(Json);
}
public async Task<bool> 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<ApiResult<UserItem>> 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<UserItem>.Failure(await ReadErrorMessageAsync(response));
var user = await response.Content.ReadFromJsonAsync<UserItem>(Json);
return user is null
? ApiResult<UserItem>.Failure(InvalidServerResponse)
: ApiResult<UserItem>.Success(user);
}
public async Task<bool> AssignRolesAsync(Guid userId, IList<string> roles)
{
var client = CreateClient();
var response = await client.PutAsJsonAsync($"api/users/{userId}/roles",
new { roles }, Json);
return response.IsSuccessStatusCode;
}
public async Task<bool> AssignSitesAsync(Guid userId, IList<Guid> siteIds)
{
var client = CreateClient();
var response = await client.PutAsJsonAsync($"api/users/{userId}/sites",
new { siteIds }, Json);
return response.IsSuccessStatusCode;
}
public async Task<PasswordResetResult?> 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<PasswordResetResult>(Json);
}
public async Task<bool> LockUserAsync(Guid userId)
{
var client = CreateClient();
var response = await client.PostAsync($"api/users/{userId}/lock", null);
return response.IsSuccessStatusCode;
}
public async Task<bool> UnlockUserAsync(Guid userId)
{
var client = CreateClient();
var response = await client.PostAsync($"api/users/{userId}/unlock", null);
return response.IsSuccessStatusCode;
}
public async Task<bool> ConfirmUserEmailAsync(Guid userId)
{
var client = CreateClient();
var response = await client.PostAsync($"api/users/{userId}/confirm-email", null);
return response.IsSuccessStatusCode;
}
/// <summary>
/// Supprime un utilisateur par son identifiant.
/// </summary>
/// <returns>null en cas de succès, sinon le message d'erreur du serveur.</returns>
public async Task<string?> 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<PagedData<SiteItem>?> GetSitesAsync(int page = 1, int pageSize = 20)
{
var client = CreateClient();
return await client.GetFromJsonAsync<PagedData<SiteItem>>(
$"api/sites?page={page}&pageSize={pageSize}", Json);
}
public async Task<SiteItem?> GetSiteAsync(Guid id)
{
var client = CreateClient();
return await client.GetFromJsonAsync<SiteItem>($"api/sites/{id}", Json);
}
public async Task<List<SiteCapacityHistoryPoint>?> GetSiteCapacityHistoryAsync(Guid id, string range)
{
var client = CreateClient();
return await client.GetFromJsonAsync<List<SiteCapacityHistoryPoint>>(
$"api/sites/{id}/capacity/history?range={Uri.EscapeDataString(range)}", Json);
}
public async Task<ApiResult<SiteWithTokenResult>> 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<SiteWithTokenResult>.Failure(await ReadErrorMessageAsync(response));
var site = await response.Content.ReadFromJsonAsync<SiteWithTokenResult>(Json);
return site is null
? ApiResult<SiteWithTokenResult>.Failure(InvalidServerResponse)
: ApiResult<SiteWithTokenResult>.Success(site);
}
public async Task<bool> 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<SiteCascadeInfo?> 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<SiteCascadeInfo>(Json);
}
public async Task<bool> DeleteSiteAsync(Guid id)
{
var client = CreateClient();
var response = await client.DeleteAsync($"api/sites/{id}");
return response.IsSuccessStatusCode;
}
public async Task<TokenResult?> 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<TokenResult>(Json);
}
// ─── Cameras ────────────────────────────────────────────────────
public async Task<PagedData<CameraItem>?> GetCamerasBySiteAsync(Guid siteId, int page = 1, int pageSize = 20)
{
var client = CreateClient();
return await client.GetFromJsonAsync<PagedData<CameraItem>>(
$"api/cameras/by-site/{siteId}?page={page}&pageSize={pageSize}", Json);
}
public async Task<CameraItem?> GetCameraAsync(Guid id)
{
var client = CreateClient();
return await client.GetFromJsonAsync<CameraItem>($"api/cameras/{id}", Json);
}
public async Task<ApiResult<Guid>> RequestCameraSnapshotAsync(Guid id)
{
var client = CreateClient();
using var response = await client.PostAsync($"api/cameras/{id}/snapshot", null);
if (!response.IsSuccessStatusCode)
return ApiResult<Guid>.Failure(await ReadErrorMessageAsync(response));
var request = await response.Content.ReadFromJsonAsync<ManualSnapshotRequestResult>(Json);
return request is null || request.RequestId == Guid.Empty
? ApiResult<Guid>.Failure(InvalidServerResponse)
: ApiResult<Guid>.Success(request.RequestId);
}
public async Task<ManualSnapshotStatusItem?> GetCameraSnapshotStatusAsync(Guid cameraId, Guid requestId)
{
var client = CreateClient();
return await client.GetFromJsonAsync<ManualSnapshotStatusItem>(
$"api/cameras/{cameraId:D}/snapshot/{requestId:D}", Json);
}
public async Task<bool> 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<ApiResult<CameraItem>> ToggleCameraStatusAsync(Guid id)
{
var client = CreateClient();
var response = await client.PostAsync($"api/cameras/{id}/toggle-status", null);
if (!response.IsSuccessStatusCode)
return ApiResult<CameraItem>.Failure(await ReadErrorMessageAsync(response));
var camera = await response.Content.ReadFromJsonAsync<CameraItem>(Json);
return camera is null
? ApiResult<CameraItem>.Failure(InvalidServerResponse)
: ApiResult<CameraItem>.Success(camera);
}
public async Task<ApiResult<CameraItem>> 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<CameraItem>.Failure(await ReadErrorMessageAsync(response));
var camera = await response.Content.ReadFromJsonAsync<CameraItem>(Json);
return camera is null
? ApiResult<CameraItem>.Failure(InvalidServerResponse)
: ApiResult<CameraItem>.Success(camera);
}
// ─── Site camera credentials ───────────────────────────────────
public async Task<List<SiteCredentialItem>> GetSiteCredentialsAsync(Guid siteId)
{
var client = CreateClient();
return await client.GetFromJsonAsync<List<SiteCredentialItem>>(
$"api/sites/{siteId}/credentials", Json) ?? [];
}
public async Task<SiteCredentialItem?> 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<SiteCredentialItem>(Json);
}
public async Task<bool> 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<List<PendingDiscoveryItem>> GetPendingDiscoveriesAsync(Guid siteId)
{
var client = CreateClient();
return await client.GetFromJsonAsync<List<PendingDiscoveryItem>>(
$"api/discovery/sites/{siteId}", Json) ?? [];
}
public async Task<ScanNowResult?> 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<ScanNowResult>(Json);
}
public async Task<bool> RejectDiscoveryAsync(Guid resultId)
{
var client = CreateClient();
var response = await client.PostAsync($"api/discovery/{resultId}/reject", null);
return response.IsSuccessStatusCode;
}
public async Task<ApiResult<CameraItem>> 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<CameraItem>.Failure(await ReadErrorMessageAsync(response));
var camera = await response.Content.ReadFromJsonAsync<CameraItem>(Json);
return camera is null
? ApiResult<CameraItem>.Failure(InvalidServerResponse)
: ApiResult<CameraItem>.Success(camera);
}
// ─── Stats ────────────────────────────────────────────────────
// ─── Audit Logs ──────────────────────────────────────────────
public async Task<PagedData<AuditLogItem>?> 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<PagedData<AuditLogItem>>(query, Json);
}
public async Task<PagedData<AgentLogItem>?> 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<PagedData<AgentLogItem>>(query, Json);
}
public async Task<StatsResult?> GetStatsAsync()
{
var client = CreateClient();
// The API wraps the payload: { "data": { ... }, "timestamp": ... }
var envelope = await client.GetFromJsonAsync<StatsEnvelope>("api/stats", Json);
return envelope?.Data;
}
public async Task<bool> DeleteCameraAsync(Guid id)
{
var client = CreateClient();
var response = await client.DeleteAsync($"api/cameras/{id}");
return response.IsSuccessStatusCode;
}
// ─── Agents ───────────────────────────────────────────────────
public async Task<AgentItem?> GetAgentAsync(Guid id)
{
var client = CreateClient();
return await client.GetFromJsonAsync<AgentItem>($"api/agents/{id}", Json);
}
public async Task<List<AgentMetricHistoryPoint>?> GetAgentMetricHistoryAsync(Guid id, string range)
{
var client = CreateClient();
return await client.GetFromJsonAsync<List<AgentMetricHistoryPoint>>(
$"api/agents/{id}/metrics/history?range={Uri.EscapeDataString(range)}", Json);
}
public async Task<PagedData<AgentItem>?> GetAgentsBySiteAsync(Guid siteId, int page = 1, int pageSize = 20)
{
var client = CreateClient();
return await client.GetFromJsonAsync<PagedData<AgentItem>>(
$"api/agents/by-site/{siteId}?page={page}&pageSize={pageSize}", Json);
}
/// <summary>List all agents across all sites (admin).</summary>
public async Task<PagedData<AgentItem>?> GetAllAgentsAsync(int page = 1, int pageSize = 20)
{
var client = CreateClient();
return await client.GetFromJsonAsync<PagedData<AgentItem>>(
$"api/agents?page={page}&pageSize={pageSize}", Json);
}
/// <summary>
/// Supprime un agent par son identifiant (soft-delete + désassignation des caméras).
/// </summary>
/// <returns>null en cas de succès, sinon le message d'erreur du serveur.</returns>
public async Task<string?> DeleteAgentAsync(Guid id)
{
var client = CreateClient();
var response = await client.DeleteAsync($"api/agents/{id}");
if (response.IsSuccessStatusCode) return null;
return await ReadErrorMessageAsync(response);
}
/// <summary>Get agent-specific KPIs for the dashboard.</summary>
public async Task<List<AgentStatItem>> GetAgentStatsAsync()
{
var client = CreateClient();
return await client.GetFromJsonAsync<List<AgentStatItem>>("api/stats/agent-stats") ?? [];
}
// ─── Updates ─────────────────────────────────────────────────
public async Task<LatestReleaseInfo?> GetLatestUpdateAsync()
{
var client = CreateClient();
return await client.GetFromJsonAsync<LatestReleaseInfo>("api/updates/latest", Json);
}
public async Task<LatestReleaseInfo?> 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<LatestReleaseInfo>(Json);
}
// ─── Settings ──────────────────────────────────────────────────
public async Task<List<AppSettingItem>> GetSettingsAsync()
{
var client = CreateClient();
return await client.GetFromJsonAsync<List<AppSettingItem>>("api/settings") ?? [];
}
public async Task<HttpResponseMessage> CreateSettingAsync(CreateAppSettingRequest request)
{
var client = CreateClient();
return await client.PostAsJsonAsync("api/settings", request);
}
public async Task<HttpResponseMessage> UpdateSettingAsync(string key, UpdateAppSettingRequest request)
{
var client = CreateClient();
return await client.PutAsJsonAsync($"api/settings/{key}", request);
}
public async Task<HttpResponseMessage> DeleteSettingAsync(string key)
{
var client = CreateClient();
return await client.DeleteAsync($"api/settings/{key}");
}
/// <summary>Test the active storage provider reachability (POST /api/settings/storage/test).</summary>
public async Task<StorageTestResult?> TestStorageAsync()
{
var client = CreateClient();
var response = await client.PostAsync("api/settings/storage/test", null);
if (!response.IsSuccessStatusCode)
return null;
return await response.Content.ReadFromJsonAsync<StorageTestResult>();
}
/// <summary>Send a test email (POST /api/settings/email/test).</summary>
public async Task<TestActionResult?> TestEmailAsync()
{
var client = CreateClient();
var response = await client.PostAsync("api/settings/email/test", null);
if (!response.IsSuccessStatusCode)
return null;
return await response.Content.ReadFromJsonAsync<TestActionResult>();
}
/// <summary>Send a test ntfy notification (POST /api/settings/ntfy/test).</summary>
public async Task<TestActionResult?> 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<TestActionResult>();
}
/// <summary>Ping the AI backends (POST /api/settings/ai/test).</summary>
public async Task<TestActionResult?> TestAiAsync()
{
var client = CreateClient();
var response = await client.PostAsync("api/settings/ai/test", null);
if (!response.IsSuccessStatusCode)
return null;
return await response.Content.ReadFromJsonAsync<TestActionResult>();
}
public async Task<HttpResponseMessage> ReloadAllConfigAsync()
{
var client = CreateClient();
return await client.PostAsync("api/settings/reload", null);
}
// ─── Agent Settings Overrides ───────────────────────────────────
public async Task<List<AgentSettingItem>> GetAgentSettingsAsync(Guid agentId)
{
var client = CreateClient();
return await client.GetFromJsonAsync<List<AgentSettingItem>>(
$"api/settings/agent/{agentId}/overrides") ?? [];
}
public async Task<HttpResponseMessage> SetAgentSettingAsync(Guid agentId, SetAgentSettingRequest request)
{
var client = CreateClient();
return await client.PutAsJsonAsync($"api/settings/agent/{agentId}/overrides", request);
}
public async Task<HttpResponseMessage> RemoveAgentSettingAsync(Guid agentId, string key)
{
var client = CreateClient();
return await client.DeleteAsync($"api/settings/agent/{agentId}/overrides/{key}");
}
public async Task<Dictionary<string, string>> GetEffectiveAgentConfigAsync(Guid agentId)
{
var client = CreateClient();
return await client.GetFromJsonAsync<Dictionary<string, string>>(
$"api/settings/agent/{agentId}") ?? [];
}
// ─── API Keys ───────────────────────────────────────────────────
public async Task<List<ApiKeyListItem>> GetApiKeysAsync()
{
var client = CreateClient();
return await client.GetFromJsonAsync<List<ApiKeyListItem>>("api/api-keys", Json) ?? [];
}
public async Task<CreateApiKeyResult?> 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<CreateApiKeyResult>(Json);
}
public async Task<bool> RevokeApiKeyAsync(Guid id)
{
var client = CreateClient();
var response = await client.DeleteAsync($"api/api-keys/{id}");
return response.IsSuccessStatusCode;
}
// ─── Persons ──────────────────────────────────────────────────────
public async Task<List<PersonClientItem>?> GetPersonsAsync(string? category = null)
{
var client = CreateClient();
var url = string.IsNullOrEmpty(category)
? "api/persons"
: $"api/persons?category={Uri.EscapeDataString(category)}";
return await client.GetFromJsonAsync<List<PersonClientItem>>(url, Json);
}
public async Task<PersonClientItem?> GetPersonAsync(Guid id)
{
var client = CreateClient();
return await client.GetFromJsonAsync<PersonClientItem>($"api/persons/{id}", Json);
}
public async Task<ApiResult<PersonClientItem>> 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<PersonClientItem>.Failure(await ReadErrorMessageAsync(response));
var person = await response.Content.ReadFromJsonAsync<PersonClientItem>(Json);
return person is null
? ApiResult<PersonClientItem>.Failure(InvalidServerResponse)
: ApiResult<PersonClientItem>.Success(person);
}
public async Task<bool> 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<bool> DeletePersonAsync(Guid id)
{
var client = CreateClient();
var response = await client.DeleteAsync($"api/persons/{id}");
return response.IsSuccessStatusCode;
}
// ─── Faces ────────────────────────────────────────────────────────
public async Task<List<KnownFaceClientItem>?> GetFacesAsync(Guid personId)
{
var client = CreateClient();
return await client.GetFromJsonAsync<List<KnownFaceClientItem>>(
$"api/persons/{personId}/faces", Json);
}
public async Task<ApiResult<KnownFaceClientItem>> 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<KnownFaceClientItem>.Failure(await ReadErrorMessageAsync(response));
var face = await response.Content.ReadFromJsonAsync<KnownFaceClientItem>(Json);
return face is null
? ApiResult<KnownFaceClientItem>.Failure(InvalidServerResponse)
: ApiResult<KnownFaceClientItem>.Success(face);
}
public async Task<bool> 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<List<VehicleClientItem>?> GetVehiclesAsync(Guid? personId = null)
{
var client = CreateClient();
var query = personId.HasValue ? $"?personId={personId.Value}" : string.Empty;
return await client.GetFromJsonAsync<List<VehicleClientItem>>($"api/vehicles{query}", Json);
}
// ─── Events ────────────────────────────────────────────────────────
public async Task<EventPageResult?> 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, Guid? personId = null)
{
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 (personId.HasValue) query += $"&personId={personId.Value}";
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<EventPageResult>($"api/events?{query}", Json);
}
public async Task<List<EventItem>?> GetRecentEventsAsync(Guid cameraId, int count = 20)
{
var client = CreateClient();
return await client.GetFromJsonAsync<List<EventItem>>($"api/events/camera/{cameraId}?count={count}", Json);
}
public async Task<EventItem?> GetEventAsync(Guid eventId)
{
var client = CreateClient();
return await client.GetFromJsonAsync<EventItem>($"api/events/{eventId}", Json);
}
// ─── Notification Config ─────────────────────────────────────────
public async Task<NotificationConfigItem?> GetNotificationConfigAsync()
{
var client = CreateClient();
return await client.GetFromJsonAsync<NotificationConfigItem>("api/notifications/config", Json);
}
public async Task<bool> 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<PagedData<UserCameraAccessResponse>?> GetUserCameraAccessAsync(Guid userId, int page = 1, int pageSize = 20)
{
var client = CreateClient();
return await client.GetFromJsonAsync<PagedData<UserCameraAccessResponse>>(
$"api/user-camera-access/user/{userId}?page={page}&pageSize={pageSize}", Json);
}
public async Task<ApiResultUserCameraAccessResponse?> 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<ApiResultUserCameraAccessResponse>(Json);
}
public async Task<bool> DeleteUserCameraAccessAsync(Guid id)
{
var client = CreateClient();
var response = await client.DeleteAsync($"api/user-camera-access/{id}");
return response.IsSuccessStatusCode;
}
public async Task<List<UserCameraAccessResponse>?> ReplaceUserCameraAccessAsync(
Guid userId, IReadOnlyList<UserCameraAccessGrantRequest> grants)
{
var client = CreateClient();
var response = await client.PutAsJsonAsync(
$"api/user-camera-access/user/{userId}", new ReplaceUserCameraAccessRequest(grants), Json);
if (!response.IsSuccessStatusCode)
return null;
return await response.Content.ReadFromJsonAsync<List<UserCameraAccessResponse>>(Json);
}
}
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; }
}
/// <summary>
/// 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).
/// </summary>
#pragma warning disable CA1000 // Do not declare static members on generic types
public sealed class ApiResult<T>
{
public bool Succeeded { get; init; }
public T? Data { get; init; }
public string? ErrorMessage { get; init; }
public static ApiResult<T> Success(T data) => new() { Succeeded = true, Data = data };
public static ApiResult<T> 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);
/// <summary>Envelope returned by GET /api/stats: { data: StatsResult, timestamp: ... }.</summary>
public record StatsEnvelope(StatsResult Data, DateTime Timestamp);
public record AgentStatItem(string StatType, string Label, int Value, string Color);
public record AgentMetricHistoryPoint(
[property: JsonPropertyName("timestampUtc")] DateTime TimestampUtc,
[property: JsonPropertyName("inventoryObservedAtUtc")] DateTime? InventoryObservedAtUtc,
[property: JsonPropertyName("logicalCores")] int? LogicalCores,
[property: JsonPropertyName("cpuUsagePercent")] double? CpuUsagePercent,
[property: JsonPropertyName("processMemoryBytes")] long? ProcessMemoryBytes,
[property: JsonPropertyName("memoryTotalBytes")] long? MemoryTotalBytes,
[property: JsonPropertyName("memoryUsedBytes")] long? MemoryUsedBytes,
[property: JsonPropertyName("diskUsagePercent")] double? DiskUsagePercent,
[property: JsonPropertyName("gpuTemperatureCelsius")] double? GpuTemperatureCelsius,
[property: JsonPropertyName("gpuUtilizationPercent")] double? GpuUtilizationPercent);
public record SiteCapacityHistoryPoint(
[property: JsonPropertyName("timestampUtc")] DateTime TimestampUtc,
[property: JsonPropertyName("inventoryObservedAtUtc")] DateTime? InventoryObservedAtUtc,
[property: JsonPropertyName("reportingAgents")] int ReportingAgents,
[property: JsonPropertyName("logicalCores")] int? LogicalCores,
[property: JsonPropertyName("memoryCapacityBytes")] long? MemoryCapacityBytes,
[property: JsonPropertyName("memoryUsedBytes")] long? MemoryUsedBytes,
[property: JsonPropertyName("averageCpuUsagePercent")] double? AverageCpuUsagePercent,
[property: JsonPropertyName("averageDiskUsagePercent")] double? AverageDiskUsagePercent,
[property: JsonPropertyName("averageGpuTemperatureCelsius")] double? AverageGpuTemperatureCelsius);
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
);
/// <summary>Résultat d'un test d'intégration (email / ntfy / IA).</summary>
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 ManualSnapshotRequestResult(
[property: JsonPropertyName("requestId")] Guid RequestId);
public record ManualSnapshotStatusItem(
[property: JsonPropertyName("requestId")] Guid RequestId,
[property: JsonPropertyName("status")] string Status,
[property: JsonPropertyName("reason")] string? Reason,
[property: JsonPropertyName("updatedAt")] DateTime UpdatedAt);
public record EventItem(
[property: JsonPropertyName("id")] Guid Id,
[property: JsonPropertyName("cameraId")] Guid CameraId,
[property: JsonPropertyName("personId")] Guid? PersonId,
[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<EventItem> 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<string> Permissions);
public record RolesListResponse(
[property: JsonPropertyName("roles")] IReadOnlyList<RoleItem> 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<PermissionItem> 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<string>? SubscribedEvents { get; set; }
}
public record UpdateNotificationConfigRequest(
bool? EmailEnabled,
string? EmailAddress,
bool? NtfyEnabled,
string? NtfyUrl,
string? NtfyTopic,
bool? DailyDigest,
bool? WeeklyDigest,
List<string>? SubscribedEvents,
string? Language = null
);
// ─── 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<string, PlatformAssetInfo> Assets { get; set; } = []; [JsonPropertyName("containerImage")] public string? ContainerImage { get; set; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; } [JsonPropertyName("updatePublicKeyPem")] public string? UpdatePublicKeyPem { 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 UserCameraAccessGrantRequest(
[property: JsonPropertyName("siteId")] Guid SiteId,
[property: JsonPropertyName("cameraId")] Guid? CameraId = null);
public record ReplaceUserCameraAccessRequest(
[property: JsonPropertyName("grants")] IReadOnlyList<UserCameraAccessGrantRequest> Grants);
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);