diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index 2946eb4..d1ead3b 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -137,13 +137,13 @@ jobs: with: fetch-depth: 0 - - uses: https://forgejo.tordais.cc/actions/setup-dotnet@v4 + - uses: actions/setup-dotnet@v4 with: dotnet-version: '10.0' - name: Cache NuGet continue-on-error: true - uses: https://forgejo.tordais.cc/actions/cache@v4 + uses: actions/cache@v4 with: path: ~/.nuget/packages key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', '**/*.slnx', '**/Directory.Build.props') }} @@ -176,7 +176,7 @@ jobs: du -sh src tests 2>/dev/null | sort -rh | head -5 - name: Upload build artifacts - uses: https://forgejo.tordais.cc/actions/upload-artifact@v3 + uses: actions/upload-artifact@v3 with: name: build-output path: | @@ -198,12 +198,12 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: https://forgejo.tordais.cc/actions/setup-dotnet@v4 + - uses: actions/setup-dotnet@v4 with: dotnet-version: '10.0' - name: Download build artifacts - uses: https://forgejo.tordais.cc/actions/download-artifact@v3 + uses: actions/download-artifact@v3 with: name: build-output @@ -264,12 +264,12 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: https://forgejo.tordais.cc/actions/setup-dotnet@v4 + - uses: actions/setup-dotnet@v4 with: dotnet-version: '10.0' - name: Download build artifacts - uses: https://forgejo.tordais.cc/actions/download-artifact@v3 + uses: actions/download-artifact@v3 with: name: build-output @@ -311,12 +311,12 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: https://forgejo.tordais.cc/actions/setup-dotnet@v4 + - uses: actions/setup-dotnet@v4 with: dotnet-version: '10.0' - name: Download build artifacts - uses: https://forgejo.tordais.cc/actions/download-artifact@v3 + uses: actions/download-artifact@v3 with: name: build-output diff --git a/.forgejo/workflows/test.yml b/.forgejo/workflows/test.yml new file mode 100644 index 0000000..7f8f62c --- /dev/null +++ b/.forgejo/workflows/test.yml @@ -0,0 +1,9 @@ +name: Test Local Checkout +on: [push] +jobs: + test: + runs-on: debian-12 + steps: + - uses: https://forgejo.tordais.cc/actions/checkout@v4 + - name: Hello + run: echo "Hello Local Checkout" diff --git a/src/Heimdall.Application/Cameras/Queries/GetCamera/GetCameraQuery.cs b/src/Heimdall.Application/Cameras/Queries/GetCamera/GetCameraQuery.cs index 8c3599f..daa21df 100644 --- a/src/Heimdall.Application/Cameras/Queries/GetCamera/GetCameraQuery.cs +++ b/src/Heimdall.Application/Cameras/Queries/GetCamera/GetCameraQuery.cs @@ -1,48 +1,8 @@ using Heimdall.Application.Common; using Heimdall.Application.DTOs; -using Heimdall.Application.Services; using MediatR; namespace Heimdall.Application.Cameras.Queries.GetCamera; +/// Get a single camera by ID, optionally filtered by user camera-access rights. public record GetCameraQuery(Guid Id, Guid? UserId = null) : IRequest>; - -public class GetCameraQueryHandler : IRequestHandler> -{ - private readonly IApplicationDbContext _db; - private readonly ICameraAccessService _cameraAccess; - - public GetCameraQueryHandler(IApplicationDbContext db, ICameraAccessService cameraAccess) - { - _db = db; - _cameraAccess = cameraAccess; - } - - public async Task> Handle(GetCameraQuery request, CancellationToken ct) - { - var camera = await _db.Cameras.FindAsync([request.Id], ct).ConfigureAwait(false); - if (camera is null) - return ServiceResult.NotFound("Camera not found"); - - // Verify camera-level access for non-admin users - if (request.UserId.HasValue) - { - var hasAccess = await _cameraAccess - .HasCameraAccessAsync(request.UserId.Value, request.Id, ct) - .ConfigureAwait(false); - if (!hasAccess) - return ServiceResult.NotFound("Camera not found"); - } - - return ServiceResult.Success(MapResponse(camera)); - } - - private static CameraResponse MapResponse(Domain.Entities.Camera c) => new( - c.Id, c.SiteId, c.AgentId, c.Name, c.Manufacturer, c.Model, - c.RtspUrl, c.SubRtspUrl, - c.Status, c.DiscoveryMethod, c.DetectedType, c.Capabilities, - c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort, - c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs, - c.LastDiscoveredAt, c.LastStreamTestAt, - c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt); -} diff --git a/src/Heimdall.Application/Cameras/Queries/GetCamera/GetCameraQueryHandler.cs b/src/Heimdall.Application/Cameras/Queries/GetCamera/GetCameraQueryHandler.cs new file mode 100644 index 0000000..8f7c957 --- /dev/null +++ b/src/Heimdall.Application/Cameras/Queries/GetCamera/GetCameraQueryHandler.cs @@ -0,0 +1,47 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Cameras.Queries.GetCamera; + +public class GetCameraQueryHandler : IRequestHandler> +{ + private readonly IApplicationDbContext _db; + private readonly ICameraAccessService _cameraAccess; + + public GetCameraQueryHandler(IApplicationDbContext db, ICameraAccessService cameraAccess) + { + _db = db; + _cameraAccess = cameraAccess; + } + + public async Task> Handle(GetCameraQuery request, CancellationToken ct) + { + var camera = await _db.Cameras.FindAsync([request.Id], ct).ConfigureAwait(false); + if (camera is null) + return ServiceResult.NotFound("Camera not found"); + + // Verify camera-level access for non-admin users + if (request.UserId.HasValue) + { + var hasAccess = await _cameraAccess + .HasCameraAccessAsync(request.UserId.Value, request.Id, ct) + .ConfigureAwait(false); + if (!hasAccess) + return ServiceResult.NotFound("Camera not found"); + } + + return ServiceResult.Success(MapResponse(camera)); + } + + private static CameraResponse MapResponse(Domain.Entities.Camera c) => new( + c.Id, c.SiteId, c.AgentId, c.Name, c.Manufacturer, c.Model, + c.RtspUrl, c.SubRtspUrl, + c.Status, c.DiscoveryMethod, c.DetectedType, c.Capabilities, + c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort, + c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs, + c.LastDiscoveredAt, c.LastStreamTestAt, + c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt); +} \ No newline at end of file diff --git a/src/Heimdall.Application/Inventory/Queries/GetInventoryStats/GetInventoryStatsQuery.cs b/src/Heimdall.Application/Inventory/Queries/GetInventoryStats/GetInventoryStatsQuery.cs new file mode 100644 index 0000000..4350204 --- /dev/null +++ b/src/Heimdall.Application/Inventory/Queries/GetInventoryStats/GetInventoryStatsQuery.cs @@ -0,0 +1,18 @@ +using Heimdall.Application.Common; +using MediatR; + +namespace Heimdall.Application.Inventory.Queries.GetInventoryStats; + +public record GetInventoryStatsQuery(Guid SiteId) : IRequest>; + +public record InventoryStatsResponse( + int TotalAgents, + int OnlineAgents, + int TotalCpus, + int TotalCores, + long TotalMemoryBytes, + long TotalDiskBytes, + int TotalGpus, + double AvgCpuUsagePercent, + double AvgMemoryUsagePercent, + double AvgDiskUsagePercent); \ No newline at end of file diff --git a/src/Heimdall.Application/Inventory/Queries/GetInventoryStats/GetInventoryStatsQueryHandler.cs b/src/Heimdall.Application/Inventory/Queries/GetInventoryStats/GetInventoryStatsQueryHandler.cs new file mode 100644 index 0000000..ec8b9fa --- /dev/null +++ b/src/Heimdall.Application/Inventory/Queries/GetInventoryStats/GetInventoryStatsQueryHandler.cs @@ -0,0 +1,44 @@ +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using MediatR; +using Microsoft.EntityFrameworkCore; +using System.Text.Json; + +namespace Heimdall.Application.Inventory.Queries.GetInventoryStats; + +public class GetInventoryStatsQueryHandler(IApplicationDbContext db) + : IRequestHandler> +{ + public async Task> Handle( + GetInventoryStatsQuery q, CancellationToken ct) + { + var agents = await db.Agents + .AsNoTracking() + .Where(a => a.SiteId == q.SiteId && !a.IsDeleted) + .ToListAsync(ct); + + if (agents.Count == 0) + return ServiceResult.Failure("No agents found for this site.", 404); + + var online = agents.Count(a => a.Status == AgentStatus.Online); + var totalCpus = agents.Count(a => a.CpuModel is not null); + var totalCores = agents.Sum(a => a.CpuCores); + var totalMem = agents.Sum(a => a.MemTotalBytes ?? 0); + var totalDisk = agents.Sum(a => + { + try { return JsonSerializer.Deserialize>(a.DiskInventoryJson ?? "[]")?.Sum(d => d.SizeBytes ?? 0) ?? 0; } + catch { return 0L; } + }); + var totalGpus = agents.Count(a => !string.IsNullOrWhiteSpace(a.GpuInventoryJson)); + var avgCpu = agents.Average(a => a.CpuUsagePercent ?? 0); + var avgMem = agents.Average(a => a.MemoryUsageBytes is null || a.MemTotalBytes is null ? 0 : (double)a.MemoryUsageBytes.Value / a.MemTotalBytes.Value * 100.0); + var avgDisk = agents.Average(a => a.DiskUsagePercent ?? 0); + + return ServiceResult.Success(new InventoryStatsResponse( + agents.Count, online, totalCpus, totalCores, + totalMem, totalDisk, totalGpus, avgCpu, avgMem, avgDisk)); + } + + private sealed record DiskInfo(string? Mount, long? SizeBytes); +} \ No newline at end of file diff --git a/src/Heimdall.Application/Sites/Queries/GetSitesByUser/GetSitesByUserQueryHandler.cs b/src/Heimdall.Application/Sites/Queries/GetSitesByUser/GetSitesByUserQueryHandler.cs new file mode 100644 index 0000000..40ed680 --- /dev/null +++ b/src/Heimdall.Application/Sites/Queries/GetSitesByUser/GetSitesByUserQueryHandler.cs @@ -0,0 +1,48 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Application.Services; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Sites.Queries.GetSitesByUser; + +public record GetSitesByUserQuery(Guid UserId, int Page = 1, int PageSize = 20) : IRequest>>; + +public class GetSitesByUserQueryHandler : IRequestHandler>> +{ + private readonly IApplicationDbContext _db; + private readonly ICameraAccessService _cameraAccess; + + public GetSitesByUserQueryHandler(IApplicationDbContext db, ICameraAccessService cameraAccess) + { + _db = db; + _cameraAccess = cameraAccess; + } + + public async Task>> Handle(GetSitesByUserQuery request, CancellationToken ct) + { + // Get all site IDs accessible to the user via the camera access service + var accessibleSiteIds = await _cameraAccess.GetAccessibleSiteIdsAsync(request.UserId, ct).ConfigureAwait(false); + + if (accessibleSiteIds.Count == 0) + return ServiceResult>.Success( + new PagedResult([], 0, request.Page, request.PageSize)); + + // Query sites belonging to those accessible site IDs with pagination + var query = _db.Sites + .AsNoTracking() + .Where(s => accessibleSiteIds.Contains(s.Id)) + .OrderBy(s => s.Name); + + var total = await query.CountAsync(ct).ConfigureAwait(false); + var items = await query + .Skip((request.Page - 1) * request.PageSize) + .Take(request.PageSize) + .Select(s => new SiteResponse( + s.Id, s.Name, s.Address, s.Timezone, s.NtfyTopic, s.Enabled, s.AutoUpdateEnabled, s.CreatedAt)) + .ToListAsync(ct); + + return ServiceResult>.Success( + new PagedResult(items, total, request.Page, request.PageSize)); + } +} \ No newline at end of file diff --git a/src/Heimdall.Web/Controllers/SitesController.cs b/src/Heimdall.Web/Controllers/SitesController.cs index 7d72916..1a4285c 100644 --- a/src/Heimdall.Web/Controllers/SitesController.cs +++ b/src/Heimdall.Web/Controllers/SitesController.cs @@ -1,4 +1,5 @@ using System.Security.Claims; +using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Application.Services; using Heimdall.Application.SiteCredentials.Queries.ListSiteCredentials; @@ -11,6 +12,7 @@ using Heimdall.Application.Sites.Commands.GenerateSiteToken; using Heimdall.Application.Sites.Queries.GetSites; using Heimdall.Application.Sites.Queries.GetSite; using Heimdall.Application.Sites.Queries.GetSiteCascadeInfo; +using Heimdall.Application.Inventory.Queries.GetInventoryStats; using Heimdall.Infrastructure.Security; using MediatR; using Microsoft.AspNetCore.Authorization; @@ -108,6 +110,19 @@ public class SitesController : ControllerBase : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } + /// Get system inventory for a site. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)] + [HttpGet("{id:guid}/inventory/stats")] + [ProducesResponseType(typeof(InventoryStatsResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task GetInventoryStats(Guid id, CancellationToken ct) + { + var result = await _mediator.Send(new GetInventoryStatsQuery(id), ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + return Ok(result.Data); + } + /// Delete a site (Admin only). [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteDelete)] [HttpDelete("{id:guid}")] @@ -135,58 +150,4 @@ public class SitesController : ControllerBase ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } - - /// List camera credential pairs declared for this site. - [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)] - [HttpGet("{id:guid}/credentials")] - [ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task ListCredentials(Guid id, CancellationToken ct) - { - var result = await _mediator.Send(new ListSiteCredentialsQuery(id), ct); - return result.IsSuccess - ? Ok(result.Data) - : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); - } - - /// Add a camera credential pair to this site (used by agent discovery). - [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)] - [HttpPost("{id:guid}/credentials")] - [ProducesResponseType(typeof(SiteCredentialResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task AddCredential( - Guid id, [FromBody] AddSiteCredentialRequest request, CancellationToken ct) - { - var command = new AddSiteCredentialCommand(id, request.Label, request.Username, request.Password); - var result = await _mediator.Send(command, ct); - if (result.IsSuccess) - { - // Les agents du site doivent re-fetch leur config pour recevoir le - // nouveau pool de credentials (enveloppe chiffrée) et enrichir les - // caméras protégées dès le prochain scan. - await _broadcast.NotifyAllAgentsReload(ct); - } - return result.IsSuccess - ? Ok(result.Data) - : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); - } - - /// Delete a camera credential pair from this site. - [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)] - [HttpDelete("{id:guid}/credentials/{credentialId:guid}")] - [ProducesResponseType(StatusCodes.Status204NoContent)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task DeleteCredential(Guid id, Guid credentialId, CancellationToken ct) - { - var result = await _mediator.Send(new DeleteSiteCredentialCommand(id, credentialId), ct); - if (result.IsSuccess) - { - // Idem : les agents doivent purger le couple supprimé de leur pool. - await _broadcast.NotifyAllAgentsReload(ct); - } - return result.IsSuccess - ? NoContent() - : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); - } -} +} \ No newline at end of file diff --git a/src/Heimdall.Web/Localization/SharedResources.en.resx b/src/Heimdall.Web/Localization/SharedResources.en.resx index b83bb4b..4ec07f6 100644 --- a/src/Heimdall.Web/Localization/SharedResources.en.resx +++ b/src/Heimdall.Web/Localization/SharedResources.en.resx @@ -79,4 +79,270 @@ Email is required + + + Sites + + + Site + + + Site Name + + + Address + + + Timezone + + + Create Site + + + Edit Site + + + Delete Site + + + Registration Token + + + Generate Token + + + + Cameras + + + Camera + + + Camera Name + + + Manufacturer + + + Model + + + RTSP URL + + + ONVIF Discovery + + + Detection Zones + + + YOLO Model + + + Confidence Threshold + + + Live Stream + + + Camera Status + + + Online + + + Offline + + + Disabled + + + + Users + + + User + + + Email + + + Roles + + + Administrator + + + Supervisor + + + Viewer + + + Status + + + Active + + + Locked + + + Pending + + + Created At + + + Actions + + + Edit User + + + Delete User + + + Lock + + + Unlock + + + Reset Password + + + Confirm Email + + + Camera Access + + + + Settings + + + Storage + + + Integrations + + + ntfy Settings + + + Email Settings + + + AI Settings + + + Agent Defaults + + + Test Connection + + + Provider + + + Local + + + S3 + + + Path + + + Bucket + + + Access Key + + + Secret Key + + + Region + + + Endpoint + + + SMTP Host + + + SMTP Port + + + Username + + + Password + + + Use SSL/TLS + + + From Address + + + From Name + + + CodeProject.AI URL + + + Ollama URL + + + Detection Enabled + + + Log Level + + + Log Retention (Days) + + + Heartbeat Interval (s) + + + + Dashboard + + + Total Sites + + + Total Cameras + + + Total Agents + + + Total Events + + + Events + + + Recent Events + + + Person + + + Vehicle + + + License Plate + + + Confidence + + + Timestamp + \ No newline at end of file diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index 7d55e1f..9d3f174 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -79,4 +79,270 @@ L'email est requis + + + Sites + + + Site + + + Nom du site + + + Adresse + + + Fuseau horaire + + + Créer un site + + + Modifier le site + + + Supprimer le site + + + Token d'enregistrement + + + Générer un token + + + + Caméras + + + Caméra + + + Nom de la caméra + + + Fabricant + + + Modèle + + + URL RTSP + + + Découverte ONVIF + + + Zones de détection + + + Modèle YOLO + + + Seuil de confiance + + + Flux en direct + + + Statut caméra + + + En ligne + + + Hors ligne + + + Désactivée + + + + Utilisateurs + + + Utilisateur + + + Email + + + Rôles + + + Administrateur + + + Superviseur + + + Visiteur + + + Statut + + + Actif + + + Verrouillé + + + En attente + + + Créé le + + + Actions + + + Modifier l'utilisateur + + + Supprimer l'utilisateur + + + Verrouiller + + + Déverrouiller + + + Réinitialiser le mot de passe + + + Confirmer l'email + + + Accès caméras + + + + Paramètres + + + Stockage + + + Intégrations + + + Configuration ntfy + + + Configuration Email + + + Configuration IA + + + Défauts agents + + + Tester la connexion + + + Fournisseur + + + Local + + + S3 + + + Chemin + + + Bucket + + + Clé d'accès + + + Clé secrète + + + Région + + + Endpoint + + + Serveur SMTP + + + Port SMTP + + + Utilisateur + + + Mot de passe + + + Utiliser SSL/TLS + + + Adresse expéditrice + + + Nom expéditeur + + + URL CodeProject.AI + + + URL Ollama + + + Détection activée + + + Niveau de log + + + Rétention logs (jours) + + + Intervalle heartbeat (s) + + + + Tableau de bord + + + Total sites + + + Total caméras + + + Total agents + + + Total événements + + + Événements + + + Événements récents + + + Personne + + + Véhicule + + + Plaque + + + Confiance + + + Horodatage + \ No newline at end of file