Further cleanup. Moved BackgroundJob Task enqueues into TaskScheduler, so I can have complete control via one interface.

This commit is contained in:
Joseph Milazzo 2021-01-18 13:53:24 -06:00
parent 825afd83a2
commit 26660a9bb3
7 changed files with 47 additions and 43 deletions

View File

@ -74,10 +74,8 @@ namespace API.Controllers
} }
_logger.LogInformation($"Created a new library: {library.Name}"); _logger.LogInformation($"Created a new library: {library.Name}");
var createdLibrary = await _unitOfWork.LibraryRepository.GetLibraryForNameAsync(library.Name); _taskScheduler.ScanLibrary(library.Id);
BackgroundJob.Enqueue(() => _directoryService.ScanLibrary(createdLibrary.Id, false));
return Ok(); return Ok();
} }
/// <summary> /// <summary>
@ -89,6 +87,7 @@ namespace API.Controllers
[HttpGet("list")] [HttpGet("list")]
public ActionResult<IEnumerable<string>> GetDirectories(string path) public ActionResult<IEnumerable<string>> GetDirectories(string path)
{ {
// TODO: Move this to another controller.
if (string.IsNullOrEmpty(path)) if (string.IsNullOrEmpty(path))
{ {
return Ok(Directory.GetLogicalDrives()); return Ok(Directory.GetLogicalDrives());
@ -102,11 +101,11 @@ namespace API.Controllers
[HttpGet] [HttpGet]
public async Task<ActionResult<IEnumerable<LibraryDto>>> GetLibraries() public async Task<ActionResult<IEnumerable<LibraryDto>>> GetLibraries()
{ {
return Ok(await _unitOfWork.LibraryRepository.GetLibrariesAsync()); return Ok(await _unitOfWork.LibraryRepository.GetLibraryDtosAsync());
} }
[Authorize(Policy = "RequireAdminRole")] [Authorize(Policy = "RequireAdminRole")]
[HttpPut("update-for")] [HttpPut("grant-access")]
public async Task<ActionResult<MemberDto>> AddLibraryToUser(UpdateLibraryForUserDto updateLibraryForUserDto) public async Task<ActionResult<MemberDto>> AddLibraryToUser(UpdateLibraryForUserDto updateLibraryForUserDto)
{ {
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(updateLibraryForUserDto.Username); var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(updateLibraryForUserDto.Username);
@ -133,19 +132,21 @@ namespace API.Controllers
[HttpPost("scan")] [HttpPost("scan")]
public ActionResult Scan(int libraryId) public ActionResult Scan(int libraryId)
{ {
BackgroundJob.Enqueue(() => _directoryService.ScanLibrary(libraryId, true)); //BackgroundJob.Enqueue(() => _directoryService.ScanLibrary(libraryId, true));
_taskScheduler.ScanLibrary(libraryId, true);
return Ok(); return Ok();
} }
[HttpGet("libraries-for")] [HttpGet("libraries-for")]
public async Task<ActionResult<IEnumerable<LibraryDto>>> GetLibrariesForUser(string username) public async Task<ActionResult<IEnumerable<LibraryDto>>> GetLibrariesForUser(string username)
{ {
return Ok(await _unitOfWork.LibraryRepository.GetLibrariesDtoForUsernameAsync(username)); return Ok(await _unitOfWork.LibraryRepository.GetLibraryDtosForUsernameAsync(username));
} }
[HttpGet("series")] [HttpGet("series")]
public async Task<ActionResult<IEnumerable<Series>>> GetSeriesForLibrary(int libraryId, bool forUser = false) public async Task<ActionResult<IEnumerable<Series>>> GetSeriesForLibrary(int libraryId, bool forUser = false)
{ {
// TODO: Move to series?
if (forUser) if (forUser)
{ {
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername()); var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
@ -167,7 +168,7 @@ namespace API.Controllers
if (result && volumes.Any()) if (result && volumes.Any())
{ {
BackgroundJob.Enqueue(() => _cacheService.CleanupVolumes(volumes)); _taskScheduler.CleanupVolumes(volumes);
} }
return Ok(result); return Ok(result);
@ -184,22 +185,17 @@ namespace API.Controllers
library.Name = libraryForUserDto.Name; library.Name = libraryForUserDto.Name;
library.Folders = libraryForUserDto.Folders.Select(s => new FolderPath() {Path = s}).ToList(); library.Folders = libraryForUserDto.Folders.Select(s => new FolderPath() {Path = s}).ToList();
_unitOfWork.LibraryRepository.Update(library); _unitOfWork.LibraryRepository.Update(library);
if (await _unitOfWork.Complete()) if (!await _unitOfWork.Complete()) return BadRequest("There was a critical issue updating the library.");
if (differenceBetweenFolders.Any())
{ {
if (differenceBetweenFolders.Any()) _taskScheduler.ScanLibrary(library.Id, true);
{
BackgroundJob.Enqueue(() => _directoryService.ScanLibrary(library.Id, true));
}
return Ok();
} }
return BadRequest("There was a critical issue updating the library."); return Ok();
} }
} }
} }

View File

@ -45,7 +45,7 @@ namespace API.Controllers
if (result) if (result)
{ {
BackgroundJob.Enqueue(() => _cacheService.CleanupVolumes(volumes)); _taskScheduler.CleanupVolumes(volumes);
} }
return Ok(result); return Ok(result);
} }

View File

@ -50,7 +50,7 @@ namespace API.Controllers
if (user == null) return BadRequest("Could not validate user"); if (user == null) return BadRequest("Could not validate user");
var libs = await _unitOfWork.LibraryRepository.GetLibrariesDtoForUsernameAsync(user.UserName); var libs = await _unitOfWork.LibraryRepository.GetLibraryDtosForUsernameAsync(user.UserName);
return Ok(libs.Any(x => x.Id == libraryId)); return Ok(libs.Any(x => x.Id == libraryId));
} }

View File

@ -26,23 +26,14 @@ namespace API.Data
_context.Entry(library).State = EntityState.Modified; _context.Entry(library).State = EntityState.Modified;
} }
public async Task<bool> SaveAllAsync() public async Task<IEnumerable<LibraryDto>> GetLibraryDtosForUsernameAsync(string userName)
{
return await _context.SaveChangesAsync() > 0;
}
public bool SaveAll()
{
return _context.SaveChanges() > 0;
}
public async Task<IEnumerable<LibraryDto>> GetLibrariesDtoForUsernameAsync(string userName)
{ {
// TODO: Speed this query up // TODO: Speed this query up
return await _context.Library return await _context.Library
.Include(l => l.AppUsers) .Include(l => l.AppUsers)
.Where(library => library.AppUsers.Any(x => x.UserName == userName)) .Where(library => library.AppUsers.Any(x => x.UserName == userName))
.ProjectTo<LibraryDto>(_mapper.ConfigurationProvider) .ProjectTo<LibraryDto>(_mapper.ConfigurationProvider)
.AsNoTracking()
.ToListAsync(); .ToListAsync();
} }
@ -62,7 +53,7 @@ namespace API.Data
return await _context.SaveChangesAsync() > 0; return await _context.SaveChangesAsync() > 0;
} }
public async Task<IEnumerable<LibraryDto>> GetLibrariesAsync() public async Task<IEnumerable<LibraryDto>> GetLibraryDtosAsync()
{ {
return await _context.Library return await _context.Library
.Include(f => f.Folders) .Include(f => f.Folders)

View File

@ -8,13 +8,11 @@ namespace API.Interfaces
public interface ILibraryRepository public interface ILibraryRepository
{ {
void Update(Library library); void Update(Library library);
Task<IEnumerable<LibraryDto>> GetLibrariesAsync(); Task<IEnumerable<LibraryDto>> GetLibraryDtosAsync();
Task<bool> LibraryExists(string libraryName); Task<bool> LibraryExists(string libraryName);
Task<Library> GetLibraryForIdAsync(int libraryId); Task<Library> GetLibraryForIdAsync(int libraryId);
bool SaveAll(); Task<IEnumerable<LibraryDto>> GetLibraryDtosForUsernameAsync(string userName);
Task<IEnumerable<LibraryDto>> GetLibrariesDtoForUsernameAsync(string userName);
Task<Library> GetLibraryForNameAsync(string libraryName); Task<Library> GetLibraryForNameAsync(string libraryName);
Task<bool> DeleteLibrary(int libraryId); Task<bool> DeleteLibrary(int libraryId);
} }
} }

View File

@ -2,6 +2,8 @@
{ {
public interface ITaskScheduler public interface ITaskScheduler
{ {
public void ScanLibrary(int libraryId, bool forceUpdate = false);
public void CleanupVolumes(int[] volumeIds);
} }
} }

View File

@ -6,19 +6,36 @@ namespace API.Services
{ {
public class TaskScheduler : ITaskScheduler public class TaskScheduler : ITaskScheduler
{ {
private readonly ICacheService _cacheService;
private readonly ILogger<TaskScheduler> _logger; private readonly ILogger<TaskScheduler> _logger;
private readonly IUnitOfWork _unitOfWork;
private readonly IDirectoryService _directoryService;
private readonly BackgroundJobServer _client; private readonly BackgroundJobServer _client;
public TaskScheduler(ICacheService cacheService, ILogger<TaskScheduler> logger) public TaskScheduler(ICacheService cacheService, ILogger<TaskScheduler> logger,
IUnitOfWork unitOfWork, IDirectoryService directoryService)
{ {
_cacheService = cacheService;
_logger = logger; _logger = logger;
_unitOfWork = unitOfWork;
_directoryService = directoryService;
_client = new BackgroundJobServer(); _client = new BackgroundJobServer();
_logger.LogInformation("Scheduling/Updating cache cleanup on a daily basis."); _logger.LogInformation("Scheduling/Updating cache cleanup on a daily basis.");
RecurringJob.AddOrUpdate(() => cacheService.Cleanup(), Cron.Daily); RecurringJob.AddOrUpdate(() => _cacheService.Cleanup(), Cron.Daily);
//RecurringJob.AddOrUpdate(() => scanService.ScanLibraries(), Cron.Daily); //RecurringJob.AddOrUpdate(() => scanService.ScanLibraries(), Cron.Daily);
} }
public void ScanLibrary(int libraryId, bool forceUpdate = false)
{
_logger.LogInformation($"Enqueuing library scan for: {libraryId}");
BackgroundJob.Enqueue(() => _directoryService.ScanLibrary(libraryId, forceUpdate));
}
public void CleanupVolumes(int[] volumeIds)
{
BackgroundJob.Enqueue(() => _cacheService.CleanupVolumes(volumeIds));
}
} }
} }