Reaperxxxx commited on
Commit
5b152aa
Β·
verified Β·
1 Parent(s): 06c1688

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +39 -29
server.js CHANGED
@@ -24,20 +24,17 @@ const axiosInstance = axios.create({
24
  httpsAgent: new https.Agent({ rejectUnauthorized: false })
25
  });
26
 
27
- // Function to generate a unique filename
28
- const generateUniqueFilename = (extension = "") => {
29
- return crypto.randomBytes(10).toString("hex") + extension;
30
- };
31
 
32
- // Function to delete a file after a delay (default: 10 minutes)
33
- const scheduleFileDeletion = (filePath, delay = 600000) => {
34
- setTimeout(() => {
35
- fs.unlink(filePath, (err) => {
36
- if (!err) {
37
- console.log(`βœ… Deleted file: ${filePath}`);
38
- }
39
- });
40
- }, delay);
41
  };
42
 
43
  // Function to convert MKV to MP4
@@ -45,7 +42,7 @@ const convertToMp4 = (inputPath, outputPath) => {
45
  return new Promise((resolve, reject) => {
46
  ffmpeg(inputPath)
47
  .output(outputPath)
48
- .outputOptions(["-c:v copy", "-c:a aac", "-strict experimental"]) // Fast conversion
49
  .on("end", () => {
50
  console.log(`βœ… Conversion complete: ${outputPath}`);
51
  resolve(outputPath);
@@ -58,32 +55,45 @@ const convertToMp4 = (inputPath, outputPath) => {
58
  });
59
  };
60
 
 
 
 
 
 
 
 
 
 
 
 
61
  // API Route to download, convert, and serve .mp4 files
62
  app.get("/download", async (req, res) => {
63
  const fileUrl = req.query.url;
64
- if (!fileUrl) {
65
- return res.status(400).json({ error: "❌ Missing URL parameter" });
 
 
66
  }
67
 
 
 
 
 
68
  try {
69
- console.log(`⬇️ Downloading: ${fileUrl}`);
70
 
71
  const response = await axiosInstance({
72
  url: fileUrl,
73
  method: "GET",
74
  responseType: "stream",
75
- headers: {
76
- "User-Agent": "Mozilla/5.0",
77
- "Accept": "*/*"
78
- }
79
  });
80
 
81
- // Generate a unique filename
82
  const isMkv = fileUrl.toLowerCase().endsWith(".mkv");
83
- const originalFilename = generateUniqueFilename(isMkv ? ".mkv" : ".mp4");
84
  const originalFilePath = path.join(DOWNLOAD_DIR, originalFilename);
85
 
86
- const mp4Filename = originalFilename.replace(".mkv", ".mp4");
87
  const mp4FilePath = path.join(DOWNLOAD_DIR, mp4Filename);
88
 
89
  const writer = fs.createWriteStream(originalFilePath);
@@ -91,13 +101,13 @@ app.get("/download", async (req, res) => {
91
 
92
  writer.on("close", async () => {
93
  const hostUrl = `${req.protocol}://${req.get("host")}`;
94
-
95
  if (isMkv) {
96
  try {
97
  await convertToMp4(originalFilePath, mp4FilePath);
98
  fs.unlinkSync(originalFilePath); // Remove MKV file
99
  } catch (error) {
100
- console.error("❌ Conversion error:", error.message);
101
  return res.status(500).json({ error: "❌ Conversion failed" });
102
  }
103
  }
@@ -105,17 +115,17 @@ app.get("/download", async (req, res) => {
105
  const servedUrl = `${hostUrl}/files/${mp4Filename}`;
106
  scheduleFileDeletion(mp4FilePath);
107
 
108
- console.log(`βœ… Download & conversion complete: ${servedUrl}`);
109
  res.json({ message: "Download & conversion complete", fileUrl: servedUrl });
110
  });
111
 
112
  writer.on("error", (err) => {
113
- console.error("❌ Error writing file:", err);
114
  res.status(500).json({ error: "Error saving file" });
115
  });
116
 
117
  } catch (error) {
118
- console.error("❌ Download error:", error.message);
119
  res.status(500).json({ error: "Failed to download file" });
120
  }
121
  });
 
24
  httpsAgent: new https.Agent({ rejectUnauthorized: false })
25
  });
26
 
27
+ // Function to generate a unique request ID
28
+ const generateRequestId = () => crypto.randomBytes(6).toString("hex");
 
 
29
 
30
+ // Function to validate URLs
31
+ const isValidUrl = (url) => {
32
+ try {
33
+ new URL(url);
34
+ return true;
35
+ } catch (error) {
36
+ return false;
37
+ }
 
38
  };
39
 
40
  // Function to convert MKV to MP4
 
42
  return new Promise((resolve, reject) => {
43
  ffmpeg(inputPath)
44
  .output(outputPath)
45
+ .outputOptions(["-c:v copy", "-c:a aac", "-strict experimental"])
46
  .on("end", () => {
47
  console.log(`βœ… Conversion complete: ${outputPath}`);
48
  resolve(outputPath);
 
55
  });
56
  };
57
 
58
+ // Function to delete files after a delay (default: 10 minutes)
59
+ const scheduleFileDeletion = (filePath, delay = 600000) => {
60
+ setTimeout(() => {
61
+ fs.unlink(filePath, (err) => {
62
+ if (!err) {
63
+ console.log(`βœ… Deleted file: ${filePath}`);
64
+ }
65
+ });
66
+ }, delay);
67
+ };
68
+
69
  // API Route to download, convert, and serve .mp4 files
70
  app.get("/download", async (req, res) => {
71
  const fileUrl = req.query.url;
72
+
73
+ // Validate URL before processing
74
+ if (!fileUrl || !isValidUrl(fileUrl)) {
75
+ return res.status(400).json({ error: "❌ Invalid or missing URL parameter" });
76
  }
77
 
78
+ // Generate a unique request ID
79
+ const requestId = generateRequestId();
80
+ console.log(`πŸ“₯ [${requestId}] Processing request for: ${fileUrl}`);
81
+
82
  try {
83
+ console.log(`⬇️ [${requestId}] Downloading: ${fileUrl}`);
84
 
85
  const response = await axiosInstance({
86
  url: fileUrl,
87
  method: "GET",
88
  responseType: "stream",
89
+ headers: { "User-Agent": "Mozilla/5.0", "Accept": "*/*" }
 
 
 
90
  });
91
 
 
92
  const isMkv = fileUrl.toLowerCase().endsWith(".mkv");
93
+ const originalFilename = `${requestId}${isMkv ? ".mkv" : ".mp4"}`;
94
  const originalFilePath = path.join(DOWNLOAD_DIR, originalFilename);
95
 
96
+ const mp4Filename = `${requestId}.mp4`;
97
  const mp4FilePath = path.join(DOWNLOAD_DIR, mp4Filename);
98
 
99
  const writer = fs.createWriteStream(originalFilePath);
 
101
 
102
  writer.on("close", async () => {
103
  const hostUrl = `${req.protocol}://${req.get("host")}`;
104
+
105
  if (isMkv) {
106
  try {
107
  await convertToMp4(originalFilePath, mp4FilePath);
108
  fs.unlinkSync(originalFilePath); // Remove MKV file
109
  } catch (error) {
110
+ console.error(`❌ [${requestId}] Conversion error:`, error.message);
111
  return res.status(500).json({ error: "❌ Conversion failed" });
112
  }
113
  }
 
115
  const servedUrl = `${hostUrl}/files/${mp4Filename}`;
116
  scheduleFileDeletion(mp4FilePath);
117
 
118
+ console.log(`βœ… [${requestId}] Download & conversion complete: ${servedUrl}`);
119
  res.json({ message: "Download & conversion complete", fileUrl: servedUrl });
120
  });
121
 
122
  writer.on("error", (err) => {
123
+ console.error(`❌ [${requestId}] Error writing file:`, err);
124
  res.status(500).json({ error: "Error saving file" });
125
  });
126
 
127
  } catch (error) {
128
+ console.error(`❌ [${requestId}] Download error:`, error.message);
129
  res.status(500).json({ error: "Failed to download file" });
130
  }
131
  });