Lots of changes to get code ready to add library.

This commit is contained in:
Joseph Milazzo 2020-12-17 11:27:19 -06:00
parent 67b97b3be2
commit d5eed4e85d
20 changed files with 570 additions and 3 deletions

View File

@ -0,0 +1,65 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using API.Data;
using API.DTOs;
using API.Entities;
using API.Extensions;
using API.Interfaces;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace API.Controllers
{
public class LibraryController : BaseApiController
{
private readonly DataContext _context;
private readonly IDirectoryService _directoryService;
private readonly ILibraryRepository _libraryRepository;
private readonly ILogger<LibraryController> _logger;
private readonly IUserRepository _userRepository;
public LibraryController(DataContext context, IDirectoryService directoryService,
ILibraryRepository libraryRepository, ILogger<LibraryController> logger, IUserRepository userRepository)
{
_context = context;
_directoryService = directoryService;
_libraryRepository = libraryRepository;
_logger = logger;
_userRepository = userRepository;
}
/// <summary>
/// Returns a list of directories for a given path. If path is empty, returns root drives.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
[HttpGet("list")]
public ActionResult<IEnumerable<string>> GetDirectories(string path)
{
// TODO: We need some sort of validation other than our auth layer
_logger.Log(LogLevel.Debug, "Listing Directories for " + path);
if (string.IsNullOrEmpty(path))
{
return Ok(Directory.GetLogicalDrives());
}
if (!Directory.Exists(@path)) return BadRequest("This is not a valid path");
return Ok(_directoryService.ListDirectory(path));
}
[HttpGet]
public async Task<ActionResult<IEnumerable<LibraryDto>>> GetLibraries()
{
return Ok(await _libraryRepository.GetLibrariesAsync());
}
}
}

View File

@ -1,10 +1,14 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using API.Data;
using API.DTOs;
using API.Entities;
using API.Extensions;
using API.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace API.Controllers
{
@ -12,11 +16,13 @@ namespace API.Controllers
{
private readonly DataContext _context;
private readonly IUserRepository _userRepository;
private readonly ILibraryRepository _libraryRepository;
public UsersController(DataContext context, IUserRepository userRepository)
public UsersController(DataContext context, IUserRepository userRepository, ILibraryRepository libraryRepository)
{
_context = context;
_userRepository = userRepository;
_libraryRepository = libraryRepository;
}
[HttpGet]
@ -24,5 +30,41 @@ namespace API.Controllers
{
return Ok(await _userRepository.GetMembersAsync());
}
[HttpPost("add-library")]
public async Task<ActionResult> AddLibrary(CreateLibraryDto createLibraryDto)
{
//_logger.Log(LogLevel.Debug, "Creating a new " + createLibraryDto.Type + " library");
var user = await _userRepository.GetUserByUsernameAsync(User.GetUsername());
if (await _libraryRepository.LibraryExists(createLibraryDto.Name))
{
return BadRequest("Library name already exists. Please choose a unique name to the server.");
}
// TODO: We probably need to clean the folders before we insert
var library = new Library()
{
Name = createLibraryDto.Name,
Type = createLibraryDto.Type,
//Folders = createLibraryDto.Folders
};
user.Libraries.Add(library);
_userRepository.Update(user);
if (await _userRepository.SaveAllAsync())
{
return Ok();
}
return BadRequest("Not implemented");
}
}
}

View File

@ -0,0 +1,19 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using API.Entities;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
namespace API.DTOs
{
public class CreateLibraryDto
{
[Required]
public string Name { get; set; }
[Required]
public LibraryType Type { get; set; }
[Required]
[MinLength(1)]
public IEnumerable<string> Folders { get; set; }
}
}

13
API/DTOs/LibraryDto.cs Normal file
View File

@ -0,0 +1,13 @@
using System.Collections.Generic;
using API.Entities;
namespace API.DTOs
{
public class LibraryDto
{
public string Name { get; set; }
public string CoverImage { get; set; }
public LibraryType Type { get; set; }
public ICollection<string> Folders { get; set; }
}
}

View File

@ -1,4 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using API.Entities;
namespace API.DTOs
{
@ -12,5 +15,6 @@ namespace API.DTOs
public DateTime Created { get; set; }
public DateTime LastActive { get; set; }
public bool IsAdmin { get; set; }
//public IEnumerable<Library> Libraries { get; set; }
}
}

View File

@ -11,5 +11,6 @@ namespace API.Data
}
public DbSet<AppUser> Users { get; set; }
public DbSet<Library> Library { get; set; }
}
}

View File

@ -0,0 +1,45 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using API.DTOs;
using API.Entities;
using API.Interfaces;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
namespace API.Data
{
public class LibraryRepository : ILibraryRepository
{
private readonly DataContext _context;
private readonly IMapper _mapper;
public LibraryRepository(DataContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public void Update(Library library)
{
_context.Entry(library).State = EntityState.Modified;
}
public async Task<bool> SaveAllAsync()
{
return await _context.SaveChangesAsync() > 0;
}
public async Task<IEnumerable<LibraryDto>> GetLibrariesAsync()
{
return await _context.Library
.Include(f => f.Folders)
.ProjectTo<LibraryDto>(_mapper.ConfigurationProvider).ToListAsync();
}
public async Task<bool> LibraryExists(string libraryName)
{
return await _context.Library.AnyAsync(x => x.Name == libraryName);
}
}
}

View File

@ -0,0 +1,128 @@
// <auto-generated />
using System;
using API.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace API.Data.Migrations
{
[DbContext(typeof(DataContext))]
[Migration("20201215195007_AddedLibrary")]
partial class AddedLibrary
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "5.0.1");
modelBuilder.Entity("API.Entities.AppUser", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("Created")
.HasColumnType("TEXT");
b.Property<bool>("IsAdmin")
.HasColumnType("INTEGER");
b.Property<DateTime>("LastActive")
.HasColumnType("TEXT");
b.Property<byte[]>("PasswordHash")
.HasColumnType("BLOB");
b.Property<byte[]>("PasswordSalt")
.HasColumnType("BLOB");
b.Property<uint>("RowVersion")
.IsConcurrencyToken()
.HasColumnType("INTEGER");
b.Property<string>("UserName")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("API.Entities.FolderPath", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int?>("LibraryId")
.HasColumnType("INTEGER");
b.Property<string>("Path")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("LibraryId");
b.ToTable("FolderPath");
});
modelBuilder.Entity("API.Entities.Library", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("AppUserId")
.HasColumnType("INTEGER");
b.Property<string>("CoverImage")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("AppUserId");
b.ToTable("Library");
});
modelBuilder.Entity("API.Entities.FolderPath", b =>
{
b.HasOne("API.Entities.Library", null)
.WithMany("Folders")
.HasForeignKey("LibraryId");
});
modelBuilder.Entity("API.Entities.Library", b =>
{
b.HasOne("API.Entities.AppUser", "AppUser")
.WithMany("Libraries")
.HasForeignKey("AppUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AppUser");
});
modelBuilder.Entity("API.Entities.AppUser", b =>
{
b.Navigation("Libraries");
});
modelBuilder.Entity("API.Entities.Library", b =>
{
b.Navigation("Folders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,71 @@
using Microsoft.EntityFrameworkCore.Migrations;
namespace API.Data.Migrations
{
public partial class AddedLibrary : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Library",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Name = table.Column<string>(type: "TEXT", nullable: true),
CoverImage = table.Column<string>(type: "TEXT", nullable: true),
Type = table.Column<int>(type: "INTEGER", nullable: false),
AppUserId = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Library", x => x.Id);
table.ForeignKey(
name: "FK_Library_Users_AppUserId",
column: x => x.AppUserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "FolderPath",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Path = table.Column<string>(type: "TEXT", nullable: true),
LibraryId = table.Column<int>(type: "INTEGER", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_FolderPath", x => x.Id);
table.ForeignKey(
name: "FK_FolderPath_Library_LibraryId",
column: x => x.LibraryId,
principalTable: "Library",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_FolderPath_LibraryId",
table: "FolderPath",
column: "LibraryId");
migrationBuilder.CreateIndex(
name: "IX_Library_AppUserId",
table: "Library",
column: "AppUserId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "FolderPath");
migrationBuilder.DropTable(
name: "Library");
}
}
}

View File

@ -48,6 +48,78 @@ namespace API.Data.Migrations
b.ToTable("Users");
});
modelBuilder.Entity("API.Entities.FolderPath", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int?>("LibraryId")
.HasColumnType("INTEGER");
b.Property<string>("Path")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("LibraryId");
b.ToTable("FolderPath");
});
modelBuilder.Entity("API.Entities.Library", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("AppUserId")
.HasColumnType("INTEGER");
b.Property<string>("CoverImage")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("AppUserId");
b.ToTable("Library");
});
modelBuilder.Entity("API.Entities.FolderPath", b =>
{
b.HasOne("API.Entities.Library", null)
.WithMany("Folders")
.HasForeignKey("LibraryId");
});
modelBuilder.Entity("API.Entities.Library", b =>
{
b.HasOne("API.Entities.AppUser", "AppUser")
.WithMany("Libraries")
.HasForeignKey("AppUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AppUser");
});
modelBuilder.Entity("API.Entities.AppUser", b =>
{
b.Navigation("Libraries");
});
modelBuilder.Entity("API.Entities.Library", b =>
{
b.Navigation("Folders");
});
#pragma warning restore 612, 618
}
}

View File

@ -48,12 +48,16 @@ namespace API.Data
public async Task<IEnumerable<MemberDto>> GetMembersAsync()
{
return await _context.Users.ProjectTo<MemberDto>(_mapper.ConfigurationProvider).ToListAsync();
return await _context.Users.Include(x => x.Libraries)
.Include(x => x.Libraries)
.ProjectTo<MemberDto>(_mapper.ConfigurationProvider)
.ToListAsync();
}
public async Task<MemberDto> GetMemberAsync(string username)
{
return await _context.Users.Where(x => x.UserName == username)
.Include(x => x.Libraries)
.ProjectTo<MemberDto>(_mapper.ConfigurationProvider)
.SingleOrDefaultAsync();
}

View File

@ -1,4 +1,6 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using API.Entities.Interfaces;
@ -14,6 +16,7 @@ namespace API.Entities
public DateTime Created { get; set; } = DateTime.Now;
public DateTime LastActive { get; set; }
public bool IsAdmin { get; set; }
public ICollection<Library> Libraries { get; set; }
[ConcurrencyCheck]
public uint RowVersion { get; set; }

View File

@ -0,0 +1,10 @@
namespace API.Entities
{
public class FolderPath
{
public int Id { get; set; }
public string Path { get; set; }
public Library Library { get; set; }
public int LibraryId { get; set; }
}
}

16
API/Entities/Library.cs Normal file
View File

@ -0,0 +1,16 @@
using System.Collections.Generic;
namespace API.Entities
{
public class Library
{
public int Id { get; set; }
public string Name { get; set; }
public string CoverImage { get; set; }
public LibraryType Type { get; set; }
public ICollection<FolderPath> Folders { get; set; }
public AppUser AppUser { get; set; }
public int AppUserId { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using System.ComponentModel;
namespace API.Entities
{
public enum LibraryType
{
[Description("Manga")]
Manga = 0,
[Description("Comic")]
Comic = 1,
[Description("Book")]
Book = 2,
[Description("Raw")]
Raw = 3
}
}

View File

@ -16,6 +16,8 @@ namespace API.Extensions
services.AddAutoMapper(typeof(AutoMapperProfiles).Assembly);
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<ITokenService, TokenService>();
services.AddScoped<IDirectoryService, DirectoryService>();
services.AddScoped<ILibraryRepository, LibraryRepository>();
services.AddDbContext<DataContext>(options =>
{
options.UseSqlite(config.GetConnectionString("DefaultConnection"));

View File

@ -1,4 +1,5 @@
using API.DTOs;
using System.Linq;
using API.DTOs;
using API.Entities;
using AutoMapper;
@ -9,6 +10,10 @@ namespace API.Helpers
public AutoMapperProfiles()
{
CreateMap<AppUser, MemberDto>();
CreateMap<Library, LibraryDto>()
.ForMember(dest => dest.Folders,
opt =>
opt.MapFrom(src => src.Folders.Select(x => x.Path).ToList()));
}
}
}

View File

@ -0,0 +1,10 @@
using System.Collections.Generic;
using System.Threading.Tasks;
namespace API.Interfaces
{
public interface IDirectoryService
{
IEnumerable<string> ListDirectory(string rootPath);
}
}

View File

@ -0,0 +1,20 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using API.DTOs;
using API.Entities;
namespace API.Interfaces
{
public interface ILibraryRepository
{
void Update(Library library);
Task<bool> SaveAllAsync();
Task<IEnumerable<LibraryDto>> GetLibrariesAsync();
/// <summary>
/// Checks to see if a library of the same name exists. We only allow unique library names, no duplicates per LibraryType.
/// </summary>
/// <param name="libraryName"></param>
/// <returns></returns>
Task<bool> LibraryExists(string libraryName);
}
}

View File

@ -0,0 +1,21 @@
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using API.Interfaces;
namespace API.Services
{
public class DirectoryService : IDirectoryService
{
public IEnumerable<string> ListDirectory(string rootPath)
{
// TODO: Filter out Hidden and System folders
// DirectoryInfo di = new DirectoryInfo(@path);
// var dirs = di.GetDirectories()
// .Where(dir => (dir.Attributes & FileAttributes.Hidden & FileAttributes.System) == 0).ToImmutableList();
//
return Directory.GetDirectories(@rootPath);
}
}
}