90 lines
No EOL
2.5 KiB
C#
90 lines
No EOL
2.5 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Mizuki.Database;
|
|
using Mizuki.Database.Models;
|
|
using Mizuki.Helpers;
|
|
|
|
namespace Mizuki.Services;
|
|
|
|
/// <summary>
|
|
/// The service managing uploads.
|
|
/// </summary>
|
|
public class UploadService(
|
|
MizukiDbContext dbContext,
|
|
DriveService driveService)
|
|
{
|
|
/// <summary>
|
|
/// Creates a new upload record for a given user.
|
|
/// </summary>
|
|
/// <param name="user">The user.</param>
|
|
/// <param name="file">The form file.</param>
|
|
/// <returns>The created upload.</returns>
|
|
public async Task<Upload?> 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();
|
|
return upload;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Deletes an upload.
|
|
/// </summary>
|
|
/// <param name="user">The user.</param>
|
|
/// <param name="filename">The name of the file that the user wishes to delete.</param>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets all the uploads for a user.
|
|
/// </summary>
|
|
/// <param name="user">The user.</param>
|
|
/// <returns>Their uploads.</returns>
|
|
public async Task<IEnumerable<Upload>> GetAllUploadsForUser(
|
|
User user)
|
|
{
|
|
return await dbContext.Uploads
|
|
.OrderByDescending(u => u.TimeOfUpload)
|
|
.Where(u => u.AuthorId == user.Id)
|
|
.ToListAsync();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets an upload by its filename.
|
|
/// </summary>
|
|
/// <param name="filename">The filename.</param>
|
|
/// <returns>The upload, if it exists.</returns>
|
|
public async Task<Upload?> GetByFilename(string filename)
|
|
{
|
|
return await dbContext.Uploads
|
|
.FirstOrDefaultAsync(u => u.Filename == filename);
|
|
}
|
|
} |