| | | 1 | | // SPDX-FileCopyrightText: 2026 Alper Çelik <alper@alper-celik.dev> |
| | | 2 | | // |
| | | 3 | | // SPDX-License-Identifier: AGPL-3.0-or-later |
| | | 4 | | |
| | | 5 | | // Mostly Ai Generated - Start |
| | | 6 | | using Api.Auth.Handlers; |
| | | 7 | | using Api.Auth.Models; |
| | | 8 | | using Api.Auth.Utils; |
| | | 9 | | using Api.Database; |
| | | 10 | | using Api.Database.Utils; |
| | | 11 | | using Api.Files.FileProviders; |
| | | 12 | | using Microsoft.AspNetCore.Http.HttpResults; |
| | | 13 | | using Microsoft.AspNetCore.Mvc; |
| | | 14 | | using Microsoft.EntityFrameworkCore; |
| | | 15 | | |
| | | 16 | | namespace Api.Files.Endpoints; |
| | | 17 | | |
| | | 18 | | public static class UploadFileEndpoint |
| | | 19 | | { |
| | | 20 | | [PermissionCheckAuthorize(UserPermissionBits.FileWrite)] |
| | | 21 | | [RequestFormLimits(MultipartBodyLengthLimit = 5L * 1024 * 1024 * 1024)] |
| | | 22 | | public static async Task< |
| | | 23 | | Results<NoContent, NotFound, Conflict, UnprocessableEntity<string>> |
| | | 24 | | > UploadFileAsync( |
| | | 25 | | Guid id, |
| | | 26 | | IFormFile file, |
| | | 27 | | [FromServices] PGContext db, |
| | | 28 | | [FromServices] ICurrentUserId userId, |
| | | 29 | | [FromServices] IEFTransactionDIAccessorService txGetter, |
| | | 30 | | [FromServices] UserFileRouter router, |
| | | 31 | | CancellationToken ct |
| | | 32 | | ) |
| | 1 | 33 | | { |
| | 1 | 34 | | var ownerId = userId.Id!.Value; |
| | | 35 | | |
| | 1 | 36 | | var uploaded = await db |
| | 1 | 37 | | .FileRecords.Where(f => f.OwnerId == ownerId && f.Id == id) |
| | 1 | 38 | | .Select(f => (bool?)f.Uploaded) |
| | 1 | 39 | | .FirstOrDefaultAsync(ct); |
| | | 40 | | |
| | 1 | 41 | | if (uploaded is null) |
| | 1 | 42 | | { |
| | 1 | 43 | | return TypedResults.NotFound(); |
| | | 44 | | } |
| | | 45 | | |
| | 1 | 46 | | if (uploaded.Value) |
| | 1 | 47 | | { |
| | 1 | 48 | | return TypedResults.Conflict(); |
| | | 49 | | } |
| | | 50 | | |
| | 1 | 51 | | var tx = await txGetter.BeginOrGetTransactionAsync(ct); |
| | | 52 | | |
| | 1 | 53 | | if (await router.SetFileAsync(ownerId, id, file.OpenReadStream(), ct) is null) |
| | 1 | 54 | | { |
| | 1 | 55 | | return TypedResults.UnprocessableEntity( |
| | 1 | 56 | | "File content did not match the declared size or SHA256" |
| | 1 | 57 | | ); |
| | | 58 | | } |
| | | 59 | | |
| | 1 | 60 | | await tx.CommitAsync(ct); |
| | 1 | 61 | | return TypedResults.NoContent(); |
| | 1 | 62 | | } |
| | | 63 | | } |
| | | 64 | | // Mostly Ai Generated - End |