Files
FitOS/api/src/lib/uploads.ts

165 lines
5.4 KiB
TypeScript

import fs from 'node:fs';
import path from 'node:path';
import { randomBytes } from 'node:crypto';
import multer from 'multer';
import { config } from '../config.js';
import { logger } from './logger.js';
export const CLAIM_FILE_MIME_TYPES = ['image/jpeg', 'image/png', 'application/pdf'] as const;
export const MAX_CLAIM_FILES = 5;
export const MAX_CLAIM_FILE_SIZE = 5 * 1024 * 1024;
/** Multer multipart limit: 5 files x 5 MB + field overhead. */
export const CLAIM_MULTIPART_LIMIT = 25 * 1024 * 1024;
export const PHOTO_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp'] as const;
export const MAX_PHOTO_FILES = 10;
export const MAX_PHOTO_FILE_SIZE = 5 * 1024 * 1024;
/** Max photos per gym (total, across uploads). */
export const MAX_GYM_PHOTOS = 20;
const EXT_BY_MIME: Record<string, string> = {
'image/jpeg': '.jpg',
'image/png': '.png',
'image/webp': '.webp',
'application/pdf': '.pdf',
};
export function storedFileName(mimeType: string): string {
return `${randomBytes(12).toString('hex')}${EXT_BY_MIME[mimeType] ?? ''}`;
}
export function claimUploadDir(claimId: string): string {
return path.join(config.uploadDir, claimId);
}
const tmpDir = path.join(config.uploadDir, 'tmp');
/**
* Multer for gym claim documents: files land in a temp dir first (the claim row —
* and thus the per-claim directory — does not exist yet); the service moves them.
*/
export const claimUpload = multer({
storage: multer.diskStorage({
destination: (_req, _file, cb) => {
try {
fs.mkdirSync(tmpDir, { recursive: true });
cb(null, tmpDir);
} catch (e) {
cb(e as Error, tmpDir);
}
},
filename: (_req, file, cb) => {
cb(null, storedFileName(file.mimetype));
},
}),
limits: { fileSize: MAX_CLAIM_FILE_SIZE, files: MAX_CLAIM_FILES },
fileFilter: (_req, file, cb) => {
if ((CLAIM_FILE_MIME_TYPES as readonly string[]).includes(file.mimetype)) cb(null, true);
else cb(new Error(`Unsupported file type: ${file.mimetype}`));
},
});
export function photoUploadDir(gymId: string): string {
return path.join(config.uploadDir, 'gyms', gymId);
}
/**
* Multer for gym gallery photos: files land in a temp dir first; the service
* moves them into UPLOAD_DIR/gyms/<gymId>/.
*/
export const gymPhotoUpload = multer({
storage: multer.diskStorage({
destination: (_req, _file, cb) => {
try {
fs.mkdirSync(tmpDir, { recursive: true });
cb(null, tmpDir);
} catch (e) {
cb(e as Error, tmpDir);
}
},
filename: (_req, file, cb) => {
cb(null, storedFileName(file.mimetype));
},
}),
limits: { fileSize: MAX_PHOTO_FILE_SIZE, files: MAX_PHOTO_FILES },
fileFilter: (_req, file, cb) => {
if ((PHOTO_MIME_TYPES as readonly string[]).includes(file.mimetype)) cb(null, true);
else cb(new Error(`Unsupported file type: ${file.mimetype}`));
},
});
/** Remove one gym photo file (best-effort — errors are logged only). */
export function removeGymPhotoFile(gymId: string, storedName: string): void {
try {
fs.rmSync(path.join(photoUploadDir(gymId), storedName), { force: true });
} catch (e) {
logger.warn({ err: e, gymId, storedName }, 'Failed to remove gym photo file');
}
}
/** Remove all of a gym's photo files (best-effort — errors are logged only). */
export function removeGymPhotoFiles(gymId: string): void {
try {
fs.rmSync(photoUploadDir(gymId), { recursive: true, force: true });
} catch (e) {
logger.warn({ err: e, gymId }, 'Failed to remove gym photo files');
}
}
/** Remove a claim's uploaded files (best-effort — errors are logged only). */
export function removeClaimFiles(claimId: string): void {
try {
fs.rmSync(claimUploadDir(claimId), { recursive: true, force: true });
} catch (e) {
logger.warn({ err: e, claimId }, 'Failed to remove claim files');
}
}
/** Remove uploaded files of all claims linked to a gym (best-effort). */
export async function removeGymClaimFiles(claimIds: string[]): Promise<void> {
for (const claimId of claimIds) removeClaimFiles(claimId);
}
/** Remove leftover temp files (after a failed claim creation). */
export function removeTmpFiles(files: { path: string }[]): void {
for (const f of files) {
try {
fs.rmSync(f.path, { force: true });
} catch (e) {
logger.warn({ err: e, path: f.path }, 'Failed to remove temp upload file');
}
}
}
/** Pliki młodsze niż stąd mogą być w trakcie żądania — nie sprzątamy ich. */
const TMP_FILE_MAX_AGE_MS = 60 * 60 * 1000;
/**
* Okresowe porządki w UPLOAD_DIR/tmp:osieroccone pliki (crash procesu w połowie
* żądania, ścieżki błędów poza obsłużonymi) nie powinny zalegać bezterminowo.
*/
export function startTmpSweeper(intervalMs = 10 * 60 * 1000): NodeJS.Timeout {
const sweep = () => {
let names: string[];
try {
names = fs.readdirSync(tmpDir);
} catch {
return; // katalog jeszcze nie istnieje — nie ma czego sprzątać
}
const cutoff = Date.now() - TMP_FILE_MAX_AGE_MS;
for (const name of names) {
const file = path.join(tmpDir, name);
try {
const st = fs.statSync(file);
if (st.isFile() && st.mtimeMs < cutoff) fs.rmSync(file, { force: true });
} catch (e) {
logger.warn({ err: e, path: file }, 'Failed to sweep temp upload file');
}
}
};
const timer = setInterval(sweep, intervalMs);
timer.unref();
void sweep();
return timer;
}