Files
GSS2Rework/GSS2.Test/ProgramImagesStorageClear.cs
T
2026-03-02 09:22:38 +03:00

99 lines
3.5 KiB
C#

using System.CommandLine;
using GSS2.Core;
using GSS2.Core.Analysis.AmineContent.Database.Calibration;
using GSS2.Core.Hardware;
using GSS2.Core.Logging;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Console;
using OpenCvSharp;
using ConsoleFormatter = GSS2.Core.Logging.ConsoleFormatter;
namespace GSS2.Test;
public partial class Program
{
private class ImagesStorateClearWorker : BackgroundService
{
private readonly ILogger<ImagesStorateClearWorker> _logger;
private readonly IHostApplicationLifetime _applicationLifetime;
private readonly AmineContentCalibrationContext _context;
private readonly ImageStorageService _imageStorageService;
public ImagesStorateClearWorker(ILogger<ImagesStorateClearWorker> logger, IHostApplicationLifetime applicationLifetime, AmineContentCalibrationContext context, ImageStorageService imageStorageService)
{
_logger = logger;
_applicationLifetime = applicationLifetime;
_context = context;
_imageStorageService = imageStorageService;
_logger.LogInformation("Initialized");
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Running images storage clear");
var unusedFiles = _imageStorageService.ListFiles()
.Select(Path.GetFileName)
.OfType<string>()
.Where(f => !_context.ImageRecords.Any(r => r.ImagePath == f));
if (unusedFiles is null || unusedFiles.Count() == 0)
{
_logger.LogInformation("Unused images not found");
_applicationLifetime.StopApplication();
return;
}
_logger.LogInformation("Found {} unused image(s):\n\t{}", unusedFiles.Count(), string.Join("\n\t", unusedFiles));
while (true)
{
_logger.LogInformation("Delete this files? (y/n) ");
var input = Console.ReadLine()?.Trim();
if (input == "y")
{
foreach (var file in unusedFiles)
_imageStorageService.Delete(file);
break;
}
if (input == "n")
break;
}
_applicationLifetime.StopApplication();
}
}
private static void ImageStorageClear(ParseResult parseResult)
{
var builder = Host.CreateApplicationBuilder();
builder.Logging.ClearProviders();
builder.Logging.AddConsole(options => options.FormatterName = nameof(ConsoleFormatter));
builder.Logging.AddConsoleFormatter<ConsoleFormatter, ConsoleFormatterOptions>();
builder.Logging.AddProvider(new FileLoggerProvider("full.log", true));
builder.Logging.AddProvider(new FileLoggerProvider("last_run.log", false));
builder.Services.AddSingleton<LibCameraLogSink>();
builder.Services.AddAmineContentCalibrationContext(builder.Configuration);
builder.Services.AddImageStorageService(new DirectoryInfo("images"));
builder.Services.AddHostedService<ImagesStorateClearWorker>();
var host = builder.Build();
using (var scope = host.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<AmineContentCalibrationContext>();
context.Database.Migrate();
}
host.Run();
}
}