Files
dnsmasq-webui/src/DnsmasqWebUI/Infrastructure/Services/Dnsmasq/Hosts/HostsFileService.cs
T
alex 2cfbaf000c Reorganise Infrastructure/Services into feature namespaces
- Move registration marker interfaces to Registration/Abstractions
- Add feature folders with Abstractions subfolders: EffectiveConfig,
  Dnsmasq/Config, Dnsmasq/Hosts, Dnsmasq/Leases, Dnsmasq/Reload,
  Logs, Updates, UI/Settings, Common/Process
- Place interfaces in each feature's Abstractions namespace; align
  implementation namespaces to folder paths
- Update Program, extensions, controllers, hubs, helpers, components,
  and tests to use new namespaces
- Remove old flat Services/Abstractions and root-level service files
2026-02-28 22:17:20 +10:00

47 lines
2.0 KiB
C#

using DnsmasqWebUI.Infrastructure.Helpers.Config;
using DnsmasqWebUI.Infrastructure.Parsers;
using DnsmasqWebUI.Infrastructure.Services.Dnsmasq.Config.Abstractions;
using DnsmasqWebUI.Infrastructure.Services.Dnsmasq.Hosts.Abstractions;
using DnsmasqWebUI.Models.Hosts;
using Microsoft.Extensions.Logging;
namespace DnsmasqWebUI.Infrastructure.Services.Dnsmasq.Hosts;
public class HostsFileService : IHostsFileService
{
private readonly IDnsmasqConfigSetService _configSetService;
private readonly IHostsCache _hostsCache;
private readonly ILogger<HostsFileService> _logger;
public HostsFileService(IDnsmasqConfigSetService configSetService, IHostsCache hostsCache, ILogger<HostsFileService> logger)
{
_configSetService = configSetService;
_hostsCache = hostsCache;
_logger = logger;
}
public async Task<IReadOnlyList<HostEntry>> ReadAsync(CancellationToken ct = default)
{
var snapshot = await _hostsCache.GetSnapshotAsync(ct);
return snapshot.ManagedEntries;
}
public async Task WriteAsync(IReadOnlyList<HostEntry> entries, CancellationToken ct = default)
{
var set = await _configSetService.GetConfigSetAsync(ct);
var path = set.ManagedHostsFilePath;
if (string.IsNullOrEmpty(path))
throw new InvalidOperationException("No managed hosts path configured. Set Dnsmasq:MainConfigPath and Dnsmasq:ManagedHostsFileName to enable hosts editing.");
var dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
var tmpPath = path + ".tmp";
var lines = entries.Select(HostsFileLineParser.ToLine).ToList();
await File.WriteAllLinesAsync(tmpPath, lines, DnsmasqFileEncoding.Utf8NoBom, ct);
File.Move(tmpPath, path, overwrite: true);
_hostsCache.NotifyWeWroteManagedHosts(entries);
_logger.LogInformation("Wrote managed hosts file: {Path}", path);
}
}