146 lines
5.8 KiB
C#
146 lines
5.8 KiB
C#
using Microsoft.Extensions.Logging;
|
||
using PARR.BLL.Services.Interfaces;
|
||
using PARR.EsppTemplateSync.Settings;
|
||
|
||
namespace PARR.EsppTemplateSync
|
||
{
|
||
internal class TemplateFileSyncer : ITemplateSyncer
|
||
{
|
||
private readonly ILogger<TemplateFileSyncer> logger;
|
||
private readonly IFileService fileService;
|
||
private readonly GlobalSettings globalSettings;
|
||
//private readonly IManager manager;
|
||
private readonly string dirPath;
|
||
private readonly string filterExtensions;
|
||
|
||
//private FileSystemWatcher? watcher;
|
||
|
||
public TemplateFileSyncer(
|
||
BLL.Settings.StorageSettings storageSettings,
|
||
ILogger<TemplateFileSyncer> logger,
|
||
IFileService fileService,
|
||
GlobalSettings globalSettings//,
|
||
// IManager manager
|
||
)
|
||
{
|
||
this.logger = logger;
|
||
this.fileService = fileService;
|
||
this.globalSettings = globalSettings;
|
||
//this.manager = manager;
|
||
if (storageSettings.EsppTemplates == null)
|
||
{
|
||
logger.LogError("Нет секции настроек хранилища. StorageSettings, EsppTemplates");
|
||
throw new Exception("Нет секции настроек хранилища. StorageSettings, EsppTemplates");
|
||
}
|
||
|
||
string dirPath = Path.Combine(storageSettings.EsppTemplates.TemplatePath);
|
||
this.dirPath = Path.Combine(storageSettings.StoragePath, dirPath);
|
||
|
||
filterExtensions = string.Join(",", storageSettings.EsppTemplates!.AllowedExtensions).Replace(".", "*.");
|
||
}
|
||
|
||
public void StartAsync()
|
||
{
|
||
//смотрим, доступна ли папка
|
||
if (!Directory.Exists(dirPath))
|
||
{
|
||
logger.LogError($"Не найдена папка: {dirPath}.");
|
||
throw new Exception($"Не найдена папка: {dirPath}.");
|
||
}
|
||
|
||
logger.LogInformation($"Запущена проверка директории. Интервал: {globalSettings.StorageSettings!.CheckIntervalSeconds} секунд. Фильтр: {filterExtensions}");
|
||
|
||
while (true)
|
||
{
|
||
//todo: new Task() ->
|
||
//await GetFilesAsync();
|
||
//await Task.Delay(globalSettings.StorageSettings!.CheckIntervalSeconds * 1000);
|
||
}
|
||
|
||
|
||
// сначала обрабатываем существующие файлы, до тех пор пока все не обработаем
|
||
// после обработки всех файлов, запускаем вотчер
|
||
//await GetFilesAsync();
|
||
|
||
// код ниже, это то что надо использовать, но в доккере не работает watcher
|
||
////--- watcher
|
||
//watcher = new FileSystemWatcher(dirPath);
|
||
//watcher.NotifyFilter = NotifyFilters.FileName;
|
||
////watcher.Changed += OnChanged;
|
||
////todo: тут await???
|
||
//watcher.Created += OnChanged;
|
||
|
||
//watcher.Filter = filterExtensions;
|
||
//watcher.EnableRaisingEvents = true;
|
||
//watcher.IncludeSubdirectories = false;
|
||
|
||
////=== watcher
|
||
|
||
//logger.LogInformation($"--- --- --- FileWatcher запущен --- --- ---");
|
||
}
|
||
|
||
|
||
public void StopAsync()
|
||
{
|
||
//watcher?.Dispose();
|
||
logger.LogInformation($"=== === === FileWatcher остановлен === === ===");
|
||
}
|
||
|
||
//private async void OnChanged(object sender, FileSystemEventArgs e)
|
||
//{
|
||
// var path = e.FullPath;
|
||
// await ParseFileAsync(path);
|
||
//}
|
||
|
||
private async Task GetFilesAsync()
|
||
{
|
||
// обрабатываем существующие файлы
|
||
var files = Directory.GetFiles(this.dirPath, filterExtensions);
|
||
|
||
//logger.LogInformation($"Запуск первоначальной загрузки файлов после старта сервиса. (До старта вотчера). Найдено файлов: {files.Length} шт.");
|
||
logger.LogInformation($"Найдено файлов: {files.Length} шт.");
|
||
|
||
foreach (var file in files)
|
||
{
|
||
if (File.Exists(file))
|
||
await ParseFileAsync(file);
|
||
else
|
||
logger.LogInformation($"Файл не найден: {file}");
|
||
}
|
||
|
||
|
||
//если были файлы, запустим еще раз ручную обработку, вдруг за это время еще загрузили, а вотчер еще не был запущен
|
||
//запускаем до тех пор, пока не останется необработанных файлов
|
||
//if (files.Any())
|
||
// await GetFilesAsync();
|
||
}
|
||
|
||
|
||
private async Task ParseFileAsync(string path)
|
||
{
|
||
logger.LogInformation($"--- --- Найден файл. Готов для парсинга {path} --- ---");
|
||
//var parseResult = await manager.ManageFileAsync(path);//parserService.ParseFileAsync(path);
|
||
|
||
//if (parseResult)
|
||
//{
|
||
// logger.LogInformation($"Парсинг успешно завершен. Удаляю файл {path}");
|
||
// var removeResult = fileService.DeleteFile(path);
|
||
//}
|
||
//else
|
||
//{
|
||
// logger.LogError($"Парсинг завершен c ошибкой. Файл не удален {path}");
|
||
//}
|
||
}
|
||
|
||
Task ITemplateSyncer.StartAsync()
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
Task ITemplateSyncer.StopAsync()
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
}
|
||
}
|