using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using RmmAgent.Models; using RmmAgent.Security; using System.Net.Http.Json; namespace RmmAgent.Services; public class EnrollmentService { private readonly ILogger _logger; private readonly IConfiguration _config; private readonly ConfigStore _configStore; private readonly MachineIdProvider _machineId; private readonly InventoryCollector _inventory; public EnrollmentService( ILogger logger, IConfiguration config, ConfigStore configStore, MachineIdProvider machineId, InventoryCollector inventory) { _logger = logger; _config = config; _configStore = configStore; _machineId = machineId; _inventory = inventory; } public async Task EnrollAsync(CancellationToken ct) { var serverUrl = _config["Rmm:ServerUrl"]?.TrimEnd('/'); var token = _config["Rmm:EnrollmentToken"]; if (string.IsNullOrWhiteSpace(serverUrl) || string.IsNullOrWhiteSpace(token)) throw new InvalidOperationException("ServerUrl ou EnrollmentToken manquant"); var sysInfo = _inventory.CollectBasic(); var machineId = _machineId.GetMachineId(); using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(60) }; var payload = new EnrollRequest( EnrollmentToken: token!, Hostname: Environment.MachineName, MachineId: machineId, OsName: sysInfo.OsName, OsVersion: sysInfo.OsVersion, OsBuild: sysInfo.OsBuild, CpuModel: sysInfo.CpuModel, RamTotalMb: sysInfo.RamTotalMb, AgentVersion: typeof(EnrollmentService).Assembly.GetName().Version?.ToString() ?? "1.0.0" ); _logger.LogInformation("Enrollment at {Url} as {Hostname}", serverUrl, payload.Hostname); var response = await http.PostAsJsonAsync($"{serverUrl}/agent/enroll", payload, ct); if (!response.IsSuccessStatusCode) { var err = await response.Content.ReadAsStringAsync(ct); throw new InvalidOperationException($"Enrollment failed ({response.StatusCode}): {err}"); } var result = await response.Content.ReadFromJsonAsync(cancellationToken: ct); if (result is null) throw new InvalidOperationException("Empty enrollment response"); _configStore.SaveAgentToken(result.AgentToken, result.AgentId); _logger.LogInformation("Enrolled as agent {AgentId}", result.AgentId); } }