using Microsoft.EntityFrameworkCore; using T120B165_ImgBoard.Data; using T120B165_ImgBoard.Models; using T120B165_ImgBoard.Utils; using File = T120B165_ImgBoard.Models.File; namespace T120B165_ImgBoard.Services; public interface IPostService { Task Create( string title, string description, List tags, User author, string fileName, string fileContentType, long fileSize); Task GetById(int postId, bool includeUnfinished = false); Task> GetAll(int pageNumber = 1); Task Delete(Post post); Task Update(Post post); } public record CreatedPost(Post Post, File File); public class PostService(ImgBoardContext context): IPostService { private const int PageSize = 20; public async Task Create( string title, string description, List tags, User author, string fileName, string fileContentType, long fileSize ) { var file = new File { OriginalFileName = fileName, Size = fileSize, ContentType = fileContentType, FilePath = Path.GetTempFileName(), CreatedDate = DateTime.Now, }; await context.Files.AddAsync(file); var entry = new Post { Title = title, Description = description, Author = author, Created = DateTime.Now, Tags = tags, File = file }; await context.Posts.AddAsync(entry); await context.SaveChangesAsync(); return new CreatedPost(entry, file); } public async Task GetById(int postId, bool includeUnfinished = false) { var query = context.Posts.Where(t => t.Id == postId); if (!includeUnfinished) { query = query.Where(t => t.File.FinishedDate != null); } return await query.Include(b => b.Author) .Include(b => b.Tags) .Include(b => b.File) .FirstOrDefaultAsync(); } public async Task> GetAll(int pageNumber = 1) { var totalCount = await context.Posts.Where(p => p.File.FinishedDate != null).CountAsync(); var items = await context.Posts .Skip((pageNumber - 1) * PageSize) .Take(PageSize) .Where(p => p.File.FinishedDate != null) .Include(b => b.Author) .Include(b => b.Tags) .Include(b => b.File) .ToListAsync(); return new PagedList(items, pageNumber, PageSize, totalCount); } public async Task Delete(Post post) { context.Posts.Remove(post); await context.SaveChangesAsync(); return true; } public async Task Update(Post post) { context.Posts.Update(post); await context.SaveChangesAsync(); return post; } }