56 lines
1.4 KiB
C#
56 lines
1.4 KiB
C#
|
|
using AZKiServer.Models;
|
|
|
|
namespace AZKiServer.Services;
|
|
|
|
public class FileScannerService(MediaService mediaService, IConfiguration config, ILogger<FileScannerService> logger) : IHostedService, IDisposable
|
|
{
|
|
private Timer? _timer;
|
|
|
|
public void Dispose()
|
|
{
|
|
_timer?.Dispose();
|
|
}
|
|
|
|
public Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
var path = config["SCAN_PATH"];
|
|
if (string.IsNullOrWhiteSpace(path))
|
|
return Task.CompletedTask;
|
|
_timer = new Timer((_) =>
|
|
{
|
|
ScanFilesAsync(path).Wait();
|
|
}, null, TimeSpan.FromMinutes(1), TimeSpan.FromHours(1));
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
_timer?.Dispose();
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
|
|
private async Task ScanFilesAsync(string path)
|
|
{
|
|
try
|
|
{
|
|
var files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
|
|
var existingFiles = await mediaService.GetExistingFilePathsAsync();
|
|
var entries = new List<MediaEntry>();
|
|
foreach (var filePath in files)
|
|
{
|
|
var relativePath = Path.GetRelativePath(path, filePath);
|
|
if (existingFiles.Contains(relativePath))
|
|
continue;
|
|
entries.Add(MediaEntry.Parse(relativePath));
|
|
}
|
|
await mediaService.AddMediaBulkAsync(entries);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "Failed to read directory contents");
|
|
}
|
|
}
|
|
}
|