From 295e62d773f3d175aae5b96a7bae292c3c39ef53 Mon Sep 17 00:00:00 2001 From: Joseph Milazzo Date: Mon, 18 Jan 2021 17:18:42 -0600 Subject: [PATCH] Fixed grant-access api and new library to properly update the db. Somehow the old way of updating db no longer works. --- API/Controllers/LibraryController.cs | 60 +++++++++++++++++----------- API/Data/LibraryRepository.cs | 7 ++++ API/Data/UserRepository.cs | 43 +++++--------------- API/Helpers/AutoMapperProfiles.cs | 7 ++++ API/Interfaces/ILibraryRepository.cs | 1 + API/Interfaces/IUserRepository.cs | 2 +- API/Services/TaskScheduler.cs | 5 +-- 7 files changed, 64 insertions(+), 61 deletions(-) diff --git a/API/Controllers/LibraryController.cs b/API/Controllers/LibraryController.cs index f72a7df63..30b946739 100644 --- a/API/Controllers/LibraryController.cs +++ b/API/Controllers/LibraryController.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -60,14 +61,7 @@ namespace API.Controllers Folders = createLibraryDto.Folders.Select(x => new FolderPath {Path = x}).ToList() }; - foreach (var admin in admins) - { - // If user is null, then set it - admin.Libraries ??= new List(); - admin.Libraries.Add(library); - } - - + _unitOfWork.LibraryRepository.Update(library); if (!await _unitOfWork.Complete()) { return BadRequest("There was a critical issue. Please try again."); @@ -87,7 +81,6 @@ namespace API.Controllers [HttpGet("list")] public ActionResult> GetDirectories(string path) { - // TODO: Move this to another controller. if (string.IsNullOrEmpty(path)) { return Ok(Directory.GetLogicalDrives()); @@ -105,26 +98,46 @@ namespace API.Controllers } [Authorize(Policy = "RequireAdminRole")] - [HttpPut("grant-access")] - public async Task> AddLibraryToUser(UpdateLibraryForUserDto updateLibraryForUserDto) + [HttpPost("grant-access")] + public async Task> UpdateUserLibraries(UpdateLibraryForUserDto updateLibraryForUserDto) { var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(updateLibraryForUserDto.Username); - if (user == null) return BadRequest("Could not validate user"); - - user.Libraries = new List(); - - foreach (var selectedLibrary in updateLibraryForUserDto.SelectedLibraries) + + var libraryString = String.Join(",", updateLibraryForUserDto.SelectedLibraries.Select(x => x.Name)); + _logger.LogInformation($"Granting user {updateLibraryForUserDto.Username} access to: {libraryString}"); + + var allLibraries = await _unitOfWork.LibraryRepository.GetLibrariesAsync(); + foreach (var library in allLibraries) { - user.Libraries.Add(_mapper.Map(selectedLibrary)); + library.AppUsers ??= new List(); + var libraryContainsUser = library.AppUsers.Any(u => u.UserName == user.UserName); + var libraryIsSelected = updateLibraryForUserDto.SelectedLibraries.Any(l => l.Id == library.Id); + if (libraryContainsUser && !libraryIsSelected) + { + // Remove + library.AppUsers.Remove(user); + } + else if (!libraryContainsUser && libraryIsSelected) + { + library.AppUsers.Add(user); + } + } + if (!_unitOfWork.HasChanges()) + { + _logger.LogInformation($"Added: {updateLibraryForUserDto.SelectedLibraries} to {updateLibraryForUserDto.Username}"); + return Ok(_mapper.Map(user)); + } + if (await _unitOfWork.Complete()) { _logger.LogInformation($"Added: {updateLibraryForUserDto.SelectedLibraries} to {updateLibraryForUserDto.Username}"); - return Ok(user); + return Ok(_mapper.Map(user)); } - + + return BadRequest("There was a critical issue. Please try again."); } @@ -132,15 +145,14 @@ namespace API.Controllers [HttpPost("scan")] public ActionResult Scan(int libraryId) { - //BackgroundJob.Enqueue(() => _directoryService.ScanLibrary(libraryId, true)); _taskScheduler.ScanLibrary(libraryId, true); return Ok(); } - [HttpGet("libraries-for")] - public async Task>> GetLibrariesForUser(string username) + [HttpGet("libraries")] + public async Task>> GetLibrariesForUser() { - return Ok(await _unitOfWork.LibraryRepository.GetLibraryDtosForUsernameAsync(username)); + return Ok(await _unitOfWork.LibraryRepository.GetLibraryDtosForUsernameAsync(User.GetUsername())); } [HttpGet("series")] diff --git a/API/Data/LibraryRepository.cs b/API/Data/LibraryRepository.cs index 32c65ffbd..5847430c4 100644 --- a/API/Data/LibraryRepository.cs +++ b/API/Data/LibraryRepository.cs @@ -36,6 +36,13 @@ namespace API.Data .AsNoTracking() .ToListAsync(); } + + public async Task> GetLibrariesAsync() + { + return await _context.Library + .Include(l => l.AppUsers) + .ToListAsync(); + } public async Task GetLibraryForNameAsync(string libraryName) { diff --git a/API/Data/UserRepository.cs b/API/Data/UserRepository.cs index 3f04505aa..72bcdcc63 100644 --- a/API/Data/UserRepository.cs +++ b/API/Data/UserRepository.cs @@ -32,27 +32,9 @@ namespace API.Data public void Delete(AppUser user) { - // TODO: Check how to implement for _userMangaer _context.AppUser.Remove(user); } - public async Task SaveAllAsync() - { - return await _context.SaveChangesAsync() > 0; - } - - public async Task> GetUsersAsync() - { - return await _userManager.Users.ToListAsync(); - //return await _context.Users.ToListAsync(); - } - - public async Task GetUserByIdAsync(int id) - { - // TODO: How to use userManager - return await _context.AppUser.FindAsync(id); - } - /// /// Gets an AppUser by username. Returns back Progress information. /// @@ -60,7 +42,7 @@ namespace API.Data /// public async Task GetUserByUsernameAsync(string username) { - return await _userManager.Users + return await _context.Users .Include(u => u.Progresses) .SingleOrDefaultAsync(x => x.UserName == username); } @@ -72,7 +54,7 @@ namespace API.Data public async Task> GetMembersAsync() { - return await _userManager.Users + return await _context.Users .Include(x => x.Libraries) .Include(r => r.UserRoles) .ThenInclude(r => r.Role) @@ -92,21 +74,16 @@ namespace API.Data Folders = l.Folders.Select(x => x.Path).ToList() }).ToList() }) + .AsNoTracking() .ToListAsync(); } - public async Task GetMemberAsync(string username) - { - return await _userManager.Users.Where(x => x.UserName == username) - .Include(x => x.Libraries) - .ProjectTo(_mapper.ConfigurationProvider) - .SingleOrDefaultAsync(); - } - - public void UpdateReadingProgressAsync(int volumeId, int pageNum) - { - - } - + // public async Task GetMemberAsync(string username) + // { + // return await _context.Users.Where(x => x.UserName == username) + // .Include(x => x.Libraries) + // .ProjectTo(_mapper.ConfigurationProvider) + // .SingleOrDefaultAsync(); + // } } } \ No newline at end of file diff --git a/API/Helpers/AutoMapperProfiles.cs b/API/Helpers/AutoMapperProfiles.cs index 714871813..586dc04f0 100644 --- a/API/Helpers/AutoMapperProfiles.cs +++ b/API/Helpers/AutoMapperProfiles.cs @@ -10,6 +10,13 @@ namespace API.Helpers public AutoMapperProfiles() { CreateMap(); + // .ForMember(dest => dest.Folders, + // opt => + // opt.MapFrom(src => src.Folders.Select(x => new FolderPath() + // { + // Path = x, + // //LibraryId = src.Id + // }).ToList())); CreateMap(); diff --git a/API/Interfaces/ILibraryRepository.cs b/API/Interfaces/ILibraryRepository.cs index 4b0a962f6..6ebc478e3 100644 --- a/API/Interfaces/ILibraryRepository.cs +++ b/API/Interfaces/ILibraryRepository.cs @@ -12,6 +12,7 @@ namespace API.Interfaces Task LibraryExists(string libraryName); Task GetLibraryForIdAsync(int libraryId); Task> GetLibraryDtosForUsernameAsync(string userName); + Task> GetLibrariesAsync(); Task GetLibraryForNameAsync(string libraryName); Task DeleteLibrary(int libraryId); } diff --git a/API/Interfaces/IUserRepository.cs b/API/Interfaces/IUserRepository.cs index 43232e9cc..01127050a 100644 --- a/API/Interfaces/IUserRepository.cs +++ b/API/Interfaces/IUserRepository.cs @@ -8,9 +8,9 @@ namespace API.Interfaces public interface IUserRepository { void Update(AppUser user); + public void Delete(AppUser user); Task GetUserByUsernameAsync(string username); Task> GetMembersAsync(); - public void Delete(AppUser user); Task> GetAdminUsersAsync(); } } \ No newline at end of file diff --git a/API/Services/TaskScheduler.cs b/API/Services/TaskScheduler.cs index aa5957f58..d33b82758 100644 --- a/API/Services/TaskScheduler.cs +++ b/API/Services/TaskScheduler.cs @@ -10,7 +10,7 @@ namespace API.Services private readonly ILogger _logger; private readonly IUnitOfWork _unitOfWork; private readonly IDirectoryService _directoryService; - private readonly BackgroundJobServer _client; + public BackgroundJobServer Client => new BackgroundJobServer(); public TaskScheduler(ICacheService cacheService, ILogger logger, IUnitOfWork unitOfWork, IDirectoryService directoryService) @@ -19,8 +19,7 @@ namespace API.Services _logger = logger; _unitOfWork = unitOfWork; _directoryService = directoryService; - _client = new BackgroundJobServer(); - + _logger.LogInformation("Scheduling/Updating cache cleanup on a daily basis."); RecurringJob.AddOrUpdate(() => _cacheService.Cleanup(), Cron.Daily); //RecurringJob.AddOrUpdate(() => scanService.ScanLibraries(), Cron.Daily);