File size: 1,935 Bytes
6e13570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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 };