Reaperxxxx commited on
Commit
2f8dcb4
Β·
verified Β·
1 Parent(s): 77483be

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +53 -80
server.js CHANGED
@@ -1,13 +1,7 @@
1
  const express = require("express");
2
- const axios = require("axios");
3
  const fs = require("fs");
4
  const path = require("path");
5
- const https = require("https");
6
- const ffmpeg = require("fluent-ffmpeg");
7
- const ffmpegStatic = require("ffmpeg-static");
8
-
9
- // Set ffmpeg binary path (needed for fluent-ffmpeg)
10
- ffmpeg.setFfmpegPath(ffmpegStatic);
11
 
12
  const app = express();
13
  const PORT = 7860;
@@ -18,24 +12,8 @@ if (!fs.existsSync(DOWNLOAD_DIR)) {
18
  fs.mkdirSync(DOWNLOAD_DIR, { recursive: true });
19
  }
20
 
21
- // Axios instance to ignore SSL certificate verification
22
- const axiosInstance = axios.create({
23
- httpsAgent: new https.Agent({ rejectUnauthorized: false })
24
- });
25
-
26
- // Function to extract filename from URL or headers
27
- const getFileName = (fileUrl, headers) => {
28
- let filename = path.basename(new URL(fileUrl).pathname);
29
-
30
- if (headers["content-disposition"]) {
31
- const match = headers["content-disposition"].match(/filename="(.+)"/);
32
- if (match) {
33
- filename = match[1];
34
- }
35
- }
36
-
37
- return filename.replace(/[<>:"/\\|?*]+/g, ""); // Remove invalid characters
38
- };
39
 
40
  // Function to delete file after a delay (default: 10 minutes)
41
  const scheduleFileDeletion = (filePath, delay = 600000) => {
@@ -48,21 +26,37 @@ const scheduleFileDeletion = (filePath, delay = 600000) => {
48
  }, delay);
49
  };
50
 
51
- // Function to convert MKV to MP4 using fluent-ffmpeg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  const convertToMp4 = (inputPath, outputPath) => {
53
  return new Promise((resolve, reject) => {
54
- ffmpeg(inputPath)
55
- .output(outputPath)
56
- .outputOptions(["-c:v copy", "-c:a aac", "-strict experimental"]) // Fast conversion
57
- .on("end", () => {
58
- console.log(`βœ… Conversion complete: ${outputPath}`);
59
- resolve(outputPath);
60
- })
61
- .on("error", (err) => {
62
- console.error(`❌ FFmpeg conversion error: ${err.message}`);
63
- reject(err);
64
- })
65
- .run();
66
  });
67
  };
68
 
@@ -76,59 +70,38 @@ app.get("/download", async (req, res) => {
76
  try {
77
  console.log(`⬇️ Downloading: ${fileUrl}`);
78
 
79
- // Request file with forced download handling
80
- const response = await axiosInstance({
81
- url: fileUrl,
82
- method: "GET",
83
- responseType: "stream",
84
- headers: {
85
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
86
- "Accept": "*/*"
87
- }
88
- });
89
-
90
- // Extract correct filename
91
- const originalFilename = getFileName(fileUrl, response.headers);
92
  const originalFilePath = path.join(DOWNLOAD_DIR, originalFilename);
93
 
94
- // Determine new filename if conversion is needed
95
  const isMkv = originalFilename.toLowerCase().endsWith(".mkv");
96
  const mp4Filename = isMkv ? originalFilename.replace(/\.mkv$/, ".mp4") : originalFilename;
97
  const mp4FilePath = path.join(DOWNLOAD_DIR, mp4Filename);
98
 
99
- // Pipe response stream to file
100
- const writer = fs.createWriteStream(originalFilePath);
101
- response.data.pipe(writer);
102
-
103
- writer.on("finish", async () => {
104
- // Dynamically get the host URL from request headers
105
- const hostUrl = `${req.protocol}://${req.get("host")}`;
106
-
107
- if (isMkv) {
108
- // Convert MKV to MP4
109
- try {
110
- await convertToMp4(originalFilePath, mp4FilePath);
111
- fs.unlinkSync(originalFilePath); // Remove original MKV after conversion
112
- } catch (error) {
113
- return res.status(500).json({ error: "❌ Conversion failed" });
114
- }
115
- }
116
 
117
- const servedUrl = `${hostUrl}/files/${mp4Filename}`;
118
- scheduleFileDeletion(mp4FilePath); // Auto-delete after 10 minutes
119
 
120
- console.log(`βœ… Download & conversion complete: ${servedUrl}`);
121
- return res.json({ message: "Download & conversion complete", fileUrl: servedUrl });
122
- });
 
 
 
 
 
 
123
 
124
- writer.on("error", (err) => {
125
- console.error("❌ Error writing file:", err);
126
- return res.status(500).json({ error: "Error saving file" });
127
- });
 
128
 
129
  } catch (error) {
130
- console.error("❌ Download error:", error.message);
131
- return res.status(500).json({ error: "Failed to download file" });
132
  }
133
  });
134
 
 
1
  const express = require("express");
 
2
  const fs = require("fs");
3
  const path = require("path");
4
+ const { exec } = require("child_process");
 
 
 
 
 
5
 
6
  const app = express();
7
  const PORT = 7860;
 
12
  fs.mkdirSync(DOWNLOAD_DIR, { recursive: true });
13
  }
14
 
15
+ // Function to extract filename from URL
16
+ const getFileName = (fileUrl) => path.basename(new URL(fileUrl).pathname);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  // Function to delete file after a delay (default: 10 minutes)
19
  const scheduleFileDeletion = (filePath, delay = 600000) => {
 
26
  }, delay);
27
  };
28
 
29
+ // Function to download file using aria2c (super fast)
30
+ const downloadFile = (fileUrl, filePath) => {
31
+ return new Promise((resolve, reject) => {
32
+ const aria2Cmd = `aria2c -x 16 -s 16 -k 1M -o "${filePath}" "${fileUrl}"`;
33
+ console.log(`πŸš€ Starting fast download: ${aria2Cmd}`);
34
+
35
+ exec(aria2Cmd, (error, stdout, stderr) => {
36
+ if (error) {
37
+ console.error(`❌ Download Error: ${error.message}`);
38
+ return reject(error);
39
+ }
40
+ console.log(`βœ… Download Complete: ${filePath}`);
41
+ resolve(filePath);
42
+ });
43
+ });
44
+ };
45
+
46
+ // Function to convert MKV to MP4 using FFmpeg (Fast Conversion)
47
  const convertToMp4 = (inputPath, outputPath) => {
48
  return new Promise((resolve, reject) => {
49
+ const ffmpegCmd = `ffmpeg -i "${inputPath}" -c:v copy -c:a aac -b:a 192k -y "${outputPath}"`;
50
+ console.log(`πŸš€ Running FFmpeg: ${ffmpegCmd}`);
51
+
52
+ exec(ffmpegCmd, (error, stdout, stderr) => {
53
+ if (error) {
54
+ console.error(`❌ FFmpeg Error: ${error.message}`);
55
+ return reject(error);
56
+ }
57
+ console.log(`βœ… FFmpeg Output: ${stdout || stderr}`);
58
+ resolve(outputPath);
59
+ });
 
60
  });
61
  };
62
 
 
70
  try {
71
  console.log(`⬇️ Downloading: ${fileUrl}`);
72
 
73
+ const originalFilename = getFileName(fileUrl);
 
 
 
 
 
 
 
 
 
 
 
 
74
  const originalFilePath = path.join(DOWNLOAD_DIR, originalFilename);
75
 
 
76
  const isMkv = originalFilename.toLowerCase().endsWith(".mkv");
77
  const mp4Filename = isMkv ? originalFilename.replace(/\.mkv$/, ".mp4") : originalFilename;
78
  const mp4FilePath = path.join(DOWNLOAD_DIR, mp4Filename);
79
 
80
+ // Start fast download with aria2c
81
+ await downloadFile(fileUrl, originalFilePath);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
+ // Dynamically get the host URL from request headers
84
+ const hostUrl = `${req.protocol}://${req.get("host")}`;
85
 
86
+ if (isMkv) {
87
+ // Convert MKV to MP4
88
+ try {
89
+ await convertToMp4(originalFilePath, mp4FilePath);
90
+ fs.unlinkSync(originalFilePath); // Remove original MKV after conversion
91
+ } catch (error) {
92
+ return res.status(500).json({ error: "❌ Conversion failed" });
93
+ }
94
+ }
95
 
96
+ const servedUrl = `${hostUrl}/files/${mp4Filename}`;
97
+ scheduleFileDeletion(mp4FilePath); // Auto-delete after 10 minutes
98
+
99
+ console.log(`βœ… Download & conversion complete: ${servedUrl}`);
100
+ return res.json({ message: "Download & conversion complete", fileUrl: servedUrl });
101
 
102
  } catch (error) {
103
+ console.error("❌ Error:", error.message);
104
+ return res.status(500).json({ error: "Download or conversion failed" });
105
  }
106
  });
107