using Microsoft.EntityFrameworkCore; using Mizuki.Database; using Mizuki.Database.Models; using Mizuki.Helpers; namespace Mizuki.Services; /// /// The service managing uploads. /// public class UploadService( MizukiDbContext dbContext, DriveService driveService) { /// /// Creates a new upload record for a given user. /// /// The user. /// The form file. /// The created upload. public async Task CreateUpload( User user, IFormFile file) { var upload = new Upload { Id = Guid.NewGuid(), Filename = Tid.NewTid().ToString(), OriginalFilename = file.FileName, SizeInBytes = file.Length, TimeOfUpload = DateTimeOffset.UtcNow, Author = user, AuthorId = user.Id }; await dbContext.Uploads.AddAsync(upload); await dbContext.SaveChangesAsync(); driveService.SaveFileByFilename(upload.Filename, file.OpenReadStream()); return upload; } /// /// Deletes an upload. /// /// The user. /// The name of the file that the user wishes to delete. public async Task DeleteUpload( User user, string filename) { var upload = await dbContext.Uploads .Where(u => u.AuthorId == user.Id && u.Filename == filename) .FirstOrDefaultAsync(); if (upload is null) return; dbContext.Uploads.Remove(upload); await dbContext.SaveChangesAsync(); driveService.DeleteFileByFilename(filename); } /// /// Gets all the uploads for a user. /// /// The user. /// Their uploads. public async Task> GetAllUploadsForUser( User user) { return await dbContext.Uploads .OrderByDescending(u => u.TimeOfUpload) .Where(u => u.AuthorId == user.Id) .ToListAsync(); } /// /// Gets an upload by its filename. /// /// The filename. /// The upload, if it exists. public async Task GetByFilename(string filename) { return await dbContext.Uploads .FirstOrDefaultAsync(u => u.Filename == filename); } }