const multer = require("multer"); const os = require("os"); const path = require("path"); const crypto = require("crypto"); // Only the file types actually needed for course content are allowed. // Uploads are only ever accepted from an authenticated admin (enforced // in the route, not here), but validating the mimetype/extension server- // side is still essential since a client can lie about content-type. const ALLOWED_MIMETYPES = new Set([ "video/mp4", "video/webm", "video/quicktime", "application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "image/png", "image/jpeg", "image/webp", ]); const MAX_FILE_SIZE_BYTES = 500 * 1024 * 1024; // 500MB — generous for course videos on Cloudinary's free tier // Files are streamed to a temp file on disk rather than buffered in // memory: buffering large videos in RAM can exhaust the memory limit on // small/free-tier hosts (e.g. a 512MB instance) well before hitting the // 500MB file-size cap. The temp file is deleted right after the upload // completes (see content.controller.js), whether it succeeds or fails. const storage = multer.diskStorage({ destination: (req, file, cb) => cb(null, os.tmpdir()), filename: (req, file, cb) => { const unique = crypto.randomBytes(16).toString("hex"); cb(null, `aynwerd-upload-${unique}${path.extname(file.originalname)}`); }, }); const upload = multer({ storage, limits: { fileSize: MAX_FILE_SIZE_BYTES, files: 1 }, fileFilter(req, file, cb) { if (!ALLOWED_MIMETYPES.has(file.mimetype)) { return cb(new Error("Unsupported file type. Allowed: mp4/webm/mov video, pdf, doc(x), ppt(x), png/jpg/webp.")); } cb(null, true); }, }); module.exports = { upload };