970 lines
40 KiB
C#
970 lines
40 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
|
|
{
|
|
private readonly IHttpClientFactory _httpFactory;
|
|
private readonly AuthState _authState;
|
|
private static readonly JsonSerializerOptions Json = new()
|
|
{
|
|
PropertyNameCaseInsensitive = true,
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
|
};
|
|
|
|
public HeimdallApiClient(IHttpClientFactory httpFactory, AuthState authState)
|
|
{
|
|
_httpFactory = httpFactory;
|
|
_authState = authState;
|
|
}
|
|
|
|
private HttpClient CreateClient()
|
|
{
|
|
var client = _httpFactory.CreateClient("HeimdallApi");
|
|
if (_authState.AccessToken is not null)
|
|
client.DefaultRequestHeaders.Authorization =
|
|
new AuthenticationHeaderValue("Bearer", _authState.AccessToken);
|
|
return client;
|
|
}
|
|
|
|
/// <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>();
|
|
|
|
var messages = new List<string>();
|
|
foreach (var field in errors.Value.EnumerateObject())
|
|
{
|
|
if (field.Value.ValueKind != JsonValueKind.Array) continue;
|
|
messages.AddRange(field.Value.EnumerateArray()
|
|
.Where(item => item.ValueKind == JsonValueKind.String
|
|
&& !string.IsNullOrWhiteSpace(item.GetString()))
|
|
.Select(item => item.GetString()!));
|
|
}
|
|
|
|
return messages.ToArray();
|
|
}
|
|
|
|
private static string FallbackErrorMessage(HttpResponseMessage response)
|
|
=> $"Erreur du serveur (HTTP {(int)response.StatusCode})";
|
|
|
|
private static string? FindStringProperty(JsonElement obj, string name)
|
|
{
|
|
foreach (var prop in obj.EnumerateObject())
|
|
{
|
|
if (string.Equals(prop.Name, name, StringComparison.OrdinalIgnoreCase)
|
|
&& prop.Value.ValueKind == JsonValueKind.String)
|
|
return prop.Value.GetString();
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
// ─── Profile ──────────────────────────────────────────────────
|
|
|
|
public async Task<UserItem?> GetMyProfileAsync()
|
|
{
|
|
var client = CreateClient();
|
|
return await client.GetFromJsonAsync<UserItem>("api/users/me", Json);
|
|
}
|
|
|
|
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() ?? [];
|
|
}
|
|
|
|
// ─── 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;
|
|
}
|
|
|
|
// ─── 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<AuthResponse?> 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<AuthResponse>(Json);
|
|
if (result is not null) _lastAuthResponse = result;
|
|
return result;
|
|
}
|
|
|
|
public async Task<AuthResponse?> Verify2faAsync(string email, string code)
|
|
{
|
|
var client = CreateClient();
|
|
var response = await client.PostAsJsonAsync("api/auth/2fa/verify", new { email, 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()
|
|
{
|
|
var client = CreateClient();
|
|
var response = await client.PostAsync("api/auth/2fa/enable", null);
|
|
if (!response.IsSuccessStatusCode) return null;
|
|
return await response.Content.ReadFromJsonAsync<Enable2faResponse>(Json);
|
|
}
|
|
|
|
public async Task<bool> Disable2faAsync()
|
|
{
|
|
var client = CreateClient();
|
|
var response = await client.PostAsync("api/auth/2fa/disable", null);
|
|
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<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;
|
|
}
|
|
|
|
// ─── 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<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("Réponse du serveur invalide.")
|
|
: ApiResult<SiteWithTokenResult>.Success(site);
|
|
}
|
|
|
|
public async Task<bool> UpdateSiteAsync(Guid id, string name, string? address, string? timezone, string? ntfyTopic = null)
|
|
{
|
|
var client = CreateClient();
|
|
var response = await client.PutAsJsonAsync($"api/sites/{id}",
|
|
new { name, address, timezone, ntfyTopic }, Json);
|
|
return response.IsSuccessStatusCode;
|
|
}
|
|
|
|
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<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>> 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("Réponse du serveur invalide.")
|
|
: 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("Réponse du serveur invalide.")
|
|
: 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)
|
|
{
|
|
var client = CreateClient();
|
|
var query = $"api/audit-logs?page={page}&pageSize={pageSize}";
|
|
if (!string.IsNullOrEmpty(resourceType)) query += $"&resourceType={resourceType}";
|
|
if (!string.IsNullOrEmpty(action)) query += $"&action={action}";
|
|
return await client.GetFromJsonAsync<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<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>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") ?? [];
|
|
}
|
|
|
|
// ─── 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()
|
|
{
|
|
var client = CreateClient();
|
|
var response = await client.PostAsync("api/settings/ntfy/test", null);
|
|
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}") ?? [];
|
|
}
|
|
|
|
// ─── 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)
|
|
{
|
|
var client = CreateClient();
|
|
var query = $"page={page}&pageSize={pageSize}";
|
|
if (cameraId.HasValue) query += $"&cameraId={cameraId}";
|
|
if (siteId.HasValue) query += $"&siteId={siteId}";
|
|
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;
|
|
}
|
|
}
|
|
|
|
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 class AuditLogItem
|
|
{
|
|
public Guid Id { get; set; }
|
|
public Guid? UserId { get; set; }
|
|
public string? UserEmail { get; set; }
|
|
public string Action { get; set; } = "";
|
|
public string ResourceType { get; set; } = "";
|
|
public string? ResourceId { get; set; }
|
|
public string? OldValue { get; set; }
|
|
public string? NewValue { get; set; }
|
|
public string? IpAddress { get; set; }
|
|
public DateTime Timestamp { get; set; }
|
|
}
|
|
|
|
public class AgentItem
|
|
{
|
|
public Guid Id { get; set; }
|
|
public Guid SiteId { get; set; }
|
|
public string 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 DateTime CreatedAt { get; set; }
|
|
public double? CpuUsagePercent { get; set; }
|
|
public long? MemoryUsageBytes { get; set; }
|
|
public double? DiskUsagePercent { get; set; }
|
|
public long? UptimeSeconds { 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; }
|
|
}
|
|
|
|
// ─── 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 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<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 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,
|
|
bool? DailyDigest,
|
|
bool? WeeklyDigest,
|
|
List<string>? SubscribedEvents
|
|
);
|