using Data_Coupler.Models;
using System.Text.Json;
namespace Data_Coupler.Services
{
///
/// Interfaccia per il servizio di gestione versione applicazione
///
public interface IVersionService
{
///
/// Ottiene le informazioni sulla versione corrente dell'applicazione
///
VersionInfo GetVersion();
///
/// Ottiene la versione formattata per display nell'UI
///
string GetDisplayVersion();
}
///
/// Servizio per gestire le informazioni di versione dell'applicazione
/// Legge i dati da version.json generato durante il build
///
public class VersionService : IVersionService
{
private readonly VersionInfo _versionInfo;
private readonly ILogger _logger;
private readonly IWebHostEnvironment _env;
public VersionService(ILogger logger, IWebHostEnvironment env)
{
_logger = logger;
_env = env;
_versionInfo = LoadVersionInfo();
}
///
/// Carica le informazioni di versione dal file version.json
///
private VersionInfo LoadVersionInfo()
{
try
{
// Cerca il file version.json nella cartella wwwroot o nella root del progetto
string? versionFilePath = null;
// Prima prova in wwwroot
if (!string.IsNullOrEmpty(_env.WebRootPath))
{
var wwwrootPath = Path.Combine(_env.WebRootPath, "version.json");
if (File.Exists(wwwrootPath))
{
versionFilePath = wwwrootPath;
}
}
// Se non trovato, prova nella root del progetto
if (versionFilePath == null)
{
var contentPath = Path.Combine(_env.ContentRootPath, "wwwroot", "version.json");
if (File.Exists(contentPath))
{
versionFilePath = contentPath;
}
}
if (versionFilePath != null && File.Exists(versionFilePath))
{
var json = File.ReadAllText(versionFilePath);
var version = JsonSerializer.Deserialize(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
if (version != null)
{
_logger.LogInformation("Version loaded from {Path}: {Version}", versionFilePath, version.GetFullVersion());
return version;
}
}
else
{
_logger.LogWarning("version.json not found. Searched in WebRootPath: {WebRoot}, ContentRootPath: {ContentRoot}",
_env.WebRootPath ?? "null", _env.ContentRootPath);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error loading version.json, using default version");
}
// Versione di default se il file non esiste o c'รจ un errore
return new VersionInfo
{
Version = "2.1.0",
CommitSha = "local",
Branch = "dev",
BuildDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
BuildEnvironment = "Local"
};
}
///
/// Ottiene le informazioni complete sulla versione
///
public VersionInfo GetVersion()
{
return _versionInfo;
}
///
/// Ottiene la versione formattata per display nell'UI
///
public string GetDisplayVersion()
{
return _versionInfo.GetShortVersion();
}
}
}