File size: 1,248 Bytes
03b405b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const fs = require("node:fs");
const { config } = require("../config/env");
const { AppError } = require("../utils/errors");

const allowedDomains = [
  "youtube.com",
  "youtu.be",
  "m.youtube.com",
  "www.youtube.com",
  "tiktok.com",
  "www.tiktok.com",
  "instagram.com",
  "www.instagram.com",
  "x.com",
  "twitter.com",
  "www.twitter.com",
  "facebook.com",
  "www.facebook.com",
  "fb.watch"
];

function validateFileSize(filePath) {
  const stat = fs.statSync(filePath);
  const max = config.limits.maxFileSizeMb * 1024 * 1024;
  if (stat.size > max) {
    throw new AppError(`File is too large. Maximum allowed size is ${config.limits.maxFileSizeMb} MB.`, "FILE_TOO_LARGE");
  }
  return stat.size;
}

function validateUrl(raw) {
  let url;
  try {
    url = new URL(raw);
  } catch {
    throw new AppError("This does not look like a valid link.", "INVALID_URL");
  }
  const host = url.hostname.toLowerCase().replace(/^www\./, "");
  const ok = allowedDomains.some((domain) => host === domain || host.endsWith(`.${domain}`));
  if (!ok) throw new AppError("This link is not from a supported video site.", "UNSUPPORTED_DOMAIN", { host });
  return url.toString();
}

module.exports = { validateFileSize, validateUrl, allowedDomains };