|
1 | 1 | import { prisma } from "../../shared/prisma"; |
2 | 2 | import { ConfigService } from "../config/service"; |
3 | | -import { RegisterFileSchema, RegisterFileInput, UpdateFileSchema } from "./dto"; |
| 3 | +import { RegisterFileSchema, RegisterFileInput, UpdateFileSchema, CheckFileInput, CheckFileSchema } from "./dto"; |
4 | 4 | import { FileService } from "./service"; |
5 | 5 | import { FastifyReply, FastifyRequest } from "fastify"; |
6 | 6 |
|
@@ -103,6 +103,56 @@ export class FileController { |
103 | 103 | } |
104 | 104 | } |
105 | 105 |
|
| 106 | + async checkFile(request: FastifyRequest, reply: FastifyReply) { |
| 107 | + try { |
| 108 | + await request.jwtVerify(); |
| 109 | + const userId = (request as any).user?.userId; |
| 110 | + if (!userId) { |
| 111 | + return reply.status(401).send({ |
| 112 | + error: "Unauthorized: a valid token is required to access this resource.", |
| 113 | + code: "unauthorized" |
| 114 | + }); |
| 115 | + } |
| 116 | + |
| 117 | + const input: CheckFileInput = CheckFileSchema.parse(request.body); |
| 118 | + |
| 119 | + const maxFileSize = BigInt(await this.configService.getValue("maxFileSize")); |
| 120 | + if (BigInt(input.size) > maxFileSize) { |
| 121 | + const maxSizeMB = Number(maxFileSize) / (1024 * 1024); |
| 122 | + return reply.status(400).send({ |
| 123 | + code: "fileSizeExceeded", |
| 124 | + error: `File size exceeds the maximum allowed size of ${maxSizeMB}MB`, |
| 125 | + details: maxSizeMB.toString(), |
| 126 | + }); |
| 127 | + } |
| 128 | + |
| 129 | + const maxTotalStorage = BigInt(await this.configService.getValue("maxTotalStoragePerUser")); |
| 130 | + |
| 131 | + const userFiles = await prisma.file.findMany({ |
| 132 | + where: { userId }, |
| 133 | + select: { size: true }, |
| 134 | + }); |
| 135 | + |
| 136 | + const currentStorage = userFiles.reduce((acc, file) => acc + file.size, BigInt(0)); |
| 137 | + |
| 138 | + if (currentStorage + BigInt(input.size) > maxTotalStorage) { |
| 139 | + const availableSpace = Number(maxTotalStorage - currentStorage) / (1024 * 1024); |
| 140 | + return reply.status(400).send({ |
| 141 | + error: `Insufficient storage space. You have ${availableSpace.toFixed(2)}MB available`, |
| 142 | + code: "insufficientStorage", |
| 143 | + details: availableSpace.toFixed(2), |
| 144 | + }); |
| 145 | + } |
| 146 | + |
| 147 | + return reply.status(201).send({ |
| 148 | + message: "File checks succeeded.", |
| 149 | + }); |
| 150 | + } catch (error: any) { |
| 151 | + console.error("Error in checkFile:", error); |
| 152 | + return reply.status(400).send({ error: error.message }); |
| 153 | + } |
| 154 | + } |
| 155 | + |
106 | 156 | async getDownloadUrl(request: FastifyRequest, reply: FastifyReply) { |
107 | 157 | try { |
108 | 158 | const { objectName: encodedObjectName } = request.params as { |
|
0 commit comments