88 lines
2.9 KiB
C#
88 lines
2.9 KiB
C#
using System.Text.Json;
|
|
using PrintService.Models;
|
|
|
|
namespace PrintService.Services;
|
|
|
|
/// <summary>
|
|
/// Loads printer-config.json (global and local), merging local over global.
|
|
/// Mirrors the same logic used in PrintServiceTray.
|
|
/// </summary>
|
|
public class ConfigurationService
|
|
{
|
|
private readonly string _globalConfigPath;
|
|
private readonly string _localConfigPath;
|
|
private readonly ILogger<ConfigurationService> _logger;
|
|
|
|
public ConfigurationService(ILogger<ConfigurationService> logger)
|
|
{
|
|
_logger = logger;
|
|
|
|
_globalConfigPath = Path.Combine(
|
|
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
|
|
"LAAPC", "printer-config.json");
|
|
|
|
_localConfigPath = Path.Combine(
|
|
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
|
"LAAPC", "printer-config.json");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Load merged configuration. Returns an empty config (not null) if no files exist.
|
|
/// </summary>
|
|
public PrinterConfiguration Load()
|
|
{
|
|
var config = new PrinterConfiguration();
|
|
|
|
if (File.Exists(_globalConfigPath))
|
|
{
|
|
try
|
|
{
|
|
var json = File.ReadAllText(_globalConfigPath);
|
|
var global = JsonSerializer.Deserialize<PrinterConfiguration>(json);
|
|
if (global != null)
|
|
config = global;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning(ex, "Failed to read global printer config from {Path}", _globalConfigPath);
|
|
}
|
|
}
|
|
|
|
if (File.Exists(_localConfigPath))
|
|
{
|
|
try
|
|
{
|
|
var json = File.ReadAllText(_localConfigPath);
|
|
var local = JsonSerializer.Deserialize<PrinterConfiguration>(json);
|
|
if (local != null)
|
|
{
|
|
// Local overrides global per document type
|
|
foreach (var kvp in local.DocumentTypes)
|
|
config.DocumentTypes[kvp.Key] = kvp.Value;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning(ex, "Failed to read local printer config from {Path}", _localConfigPath);
|
|
}
|
|
}
|
|
|
|
if (config.DocumentTypes.Count == 0)
|
|
_logger.LogWarning("No document types found in printer-config.json. Checked: {Global} and {Local}",
|
|
_globalConfigPath, _localConfigPath);
|
|
|
|
return config;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get a single document type config by name (case-insensitive).
|
|
/// </summary>
|
|
public DocumentTypeConfig? GetDocumentType(string documentType)
|
|
{
|
|
var config = Load();
|
|
return config.DocumentTypes
|
|
.FirstOrDefault(kvp => kvp.Key.Equals(documentType, StringComparison.OrdinalIgnoreCase))
|
|
.Value;
|
|
}
|
|
}
|