Added implementation to FileSystemScanService

This commit is contained in:
Samuele Lorefice
2025-07-08 17:30:26 +02:00
parent 607fef4cb0
commit ce7dba34c8
2 changed files with 46 additions and 13 deletions
@@ -5,11 +5,16 @@ using static System.String;
namespace Lactose.Services;
public class FileSystemScanService(
ILogger<FileSystemScanService> logger,
public class FileSystemScannerService(
ILogger<FileSystemScannerService> logger,
IAssetRepository assetRepository,
IFolderRepository folderRepository
) : BackgroundService {
public bool IsRunning { get; private set; } = false;
public bool IsInitialized { get; private set; } = false;
//TODO: Make this configurable
public TimeSpan ScanInterval { get; private set; } = TimeSpan.FromMinutes(30);
List<Folder> folders = [];
readonly List<Task> tasks = [];
@@ -108,17 +113,43 @@ public class FileSystemScanService(
new("video/x-msvideo", [".avi"]),
new("video/x-sgi-movie", [".movie"])
];
protected override Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellationRequested && !tasks.All(task => task.IsCompleted)) {
logger.LogInformation("Starting scan");
folders = folderRepository.GetAll().ToList();
// Launch a folder scan for each folder, passing the stopping token to each task
folders.ForEach(folder => { tasks.Add(Task.Run(() => ScanFolder(folder.BasePath), stoppingToken)); });
}
return Task.CompletedTask;
protected override Task ExecuteAsync(CancellationToken stoppingToken) {
var service = new Task(() => ServiceLogic(stoppingToken));
service.Start();
return service;
}
//TODO: This really needs a decent name.
void ServiceLogic(CancellationToken stoppingToken) {
PeriodicTimer scanTimer;
logger.LogInformation("Filesystem Scan Service starting...");
//TODO: fetch scan interval from DB if possible
// settingsRepository.GetSetting("scanInterval", out string? scanInterval);
scanTimer = new (ScanInterval);
logger.LogInformation($"Service will scan every {ScanInterval.TotalMinutes} minutes.");
IsInitialized = true;
while (!stoppingToken.IsCancellationRequested) {
logger.LogInformation("Retrieving folder paths to scan...");
folders = folderRepository.GetAll().ToList();
// Wait for all tasks to complete before starting a new scan
if(tasks.Count > 0) {
logger.LogInformation("Waiting for {count} tasks to complete...", tasks.Count);
Task.WaitAll(tasks.ToArray(), stoppingToken);
IsRunning = false;
}
if (folders.Count != 0) {
logger.LogInformation("Found {count} folders to scan.", folders.Count);
logger.LogInformation("Starting Tasks for scanning folders...");
// Launch a folder scan for each folder, passing the stopping token to each task
folders.ForEach(folder => { tasks.Add(Task.Run(() => ScanFolder(folder.BasePath), stoppingToken)); });
IsRunning = true;
} else {
logger.LogWarning("No folders to scan. Waiting for next scan interval...");
scanTimer.WaitForNextTickAsync(stoppingToken);
}
}
}
void ScanFolder(string path) {