Reaperxxxx commited on
Commit
1a7be53
·
verified ·
1 Parent(s): aa6ae8d

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +48 -52
server.js CHANGED
@@ -2,7 +2,7 @@ const express = require("express");
2
  const axios = require("axios");
3
  const fs = require("fs");
4
  const path = require("path");
5
- const progress = require("progress-stream");
6
 
7
  const app = express();
8
  const PORT = 7860;
@@ -10,18 +10,38 @@ const DOWNLOAD_DIR = path.join(__dirname, "downloads");
10
 
11
  // Ensure the downloads directory exists
12
  if (!fs.existsSync(DOWNLOAD_DIR)) {
13
- fs.mkdirSync(DOWNLOAD_DIR);
14
  }
15
 
16
- // Function to format bytes into human-readable size
17
- function formatBytes(bytes, decimals = 2) {
18
- if (bytes === 0) return "0 Bytes";
19
- const k = 1024;
20
- const dm = decimals < 0 ? 0 : decimals;
21
- const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
22
- const i = Math.floor(Math.log(bytes) / Math.log(k));
23
- return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
24
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
  // API Route to download and serve .mkv files
27
  app.get("/download", async (req, res) => {
@@ -31,55 +51,31 @@ app.get("/download", async (req, res) => {
31
  }
32
 
33
  try {
34
- // Get filename from URL
35
- const filename = path.basename(new URL(fileUrl).pathname);
36
- const filePath = path.join(DOWNLOAD_DIR, filename);
37
 
38
- // Start the download request
39
- const response = await axios({
40
  url: fileUrl,
41
  method: "GET",
42
- responseType: "stream"
43
- });
44
-
45
- // Get file size from headers
46
- const totalSize = parseInt(response.headers["content-length"], 10);
47
- console.log(`Downloading: ${filename} (${formatBytes(totalSize)})`);
48
-
49
- // Progress tracking
50
- const progressStream = progress({
51
- length: totalSize,
52
- time: 1000 // Update every second
53
  });
54
 
55
- progressStream.on("progress", (progress) => {
56
- const speed = formatBytes(progress.speed) + "/s";
57
- const downloaded = formatBytes(progress.transferred);
58
- const percent = progress.percentage.toFixed(2);
59
- const timeLeft = progress.eta ? progress.eta.toFixed(2) + "s" : "Calculating...";
60
- console.log(`Progress: ${percent}% | Speed: ${speed} | Downloaded: ${downloaded} | Time Left: ${timeLeft}`);
61
- });
62
 
63
- // Pipe the download stream through progress tracking and into a file
64
  const writer = fs.createWriteStream(filePath);
65
- response.data.pipe(progressStream).pipe(writer);
66
 
67
  writer.on("finish", () => {
68
- const fileUrl = `http://localhost:${PORT}/files/${filename}`;
69
- console.log(`Download complete: ${fileUrl}`);
70
-
71
- // Schedule file deletion after 10 minutes (600,000 ms)
72
- setTimeout(() => {
73
- fs.unlink(filePath, (err) => {
74
- if (err) {
75
- console.error(`Error deleting file ${filename}:`, err);
76
- } else {
77
- console.log(`File ${filename} deleted after 10 minutes.`);
78
- }
79
- });
80
- }, 600000); // 10 minutes
81
-
82
- return res.json({ message: "Download complete", fileUrl });
83
  });
84
 
85
  writer.on("error", (err) => {
@@ -88,7 +84,7 @@ app.get("/download", async (req, res) => {
88
  });
89
 
90
  } catch (error) {
91
- console.error("Download error:", error);
92
  return res.status(500).json({ error: "Failed to download file" });
93
  }
94
  });
 
2
  const axios = require("axios");
3
  const fs = require("fs");
4
  const path = require("path");
5
+ const https = require("https");
6
 
7
  const app = express();
8
  const PORT = 7860;
 
10
 
11
  // Ensure the downloads directory exists
12
  if (!fs.existsSync(DOWNLOAD_DIR)) {
13
+ fs.mkdirSync(DOWNLOAD_DIR, { recursive: true });
14
  }
15
 
16
+ // Axios instance to ignore SSL certificate verification
17
+ const axiosInstance = axios.create({
18
+ httpsAgent: new https.Agent({ rejectUnauthorized: false })
19
+ });
20
+
21
+ // Function to extract filename from URL or headers
22
+ const getFileName = (fileUrl, headers) => {
23
+ let filename = path.basename(new URL(fileUrl).pathname);
24
+
25
+ if (headers["content-disposition"]) {
26
+ const match = headers["content-disposition"].match(/filename="(.+)"/);
27
+ if (match) {
28
+ filename = match[1];
29
+ }
30
+ }
31
+
32
+ return filename.replace(/[<>:"/\\|?*]+/g, ""); // Remove invalid characters
33
+ };
34
+
35
+ // Function to delete file after a delay
36
+ const scheduleFileDeletion = (filePath, delay = 600000) => { // 10 minutes
37
+ setTimeout(() => {
38
+ fs.unlink(filePath, (err) => {
39
+ if (!err) {
40
+ console.log(`Deleted file: ${filePath}`);
41
+ }
42
+ });
43
+ }, delay);
44
+ };
45
 
46
  // API Route to download and serve .mkv files
47
  app.get("/download", async (req, res) => {
 
51
  }
52
 
53
  try {
54
+ console.log(`Downloading: ${fileUrl}`);
 
 
55
 
56
+ // Request file with forced download handling
57
+ const response = await axiosInstance({
58
  url: fileUrl,
59
  method: "GET",
60
+ responseType: "stream",
61
+ headers: {
62
+ "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",
63
+ "Accept": "*/*"
64
+ }
 
 
 
 
 
 
65
  });
66
 
67
+ // Extract correct filename
68
+ const filename = getFileName(fileUrl, response.headers);
69
+ const filePath = path.join(DOWNLOAD_DIR, filename);
 
 
 
 
70
 
71
+ // Pipe response stream to file
72
  const writer = fs.createWriteStream(filePath);
73
+ response.data.pipe(writer);
74
 
75
  writer.on("finish", () => {
76
+ const servedUrl = `http://localhost:${PORT}/files/${filename}`;
77
+ scheduleFileDeletion(filePath); // Auto-delete after 10 minutes
78
+ return res.json({ message: "Download complete", fileUrl: servedUrl });
 
 
 
 
 
 
 
 
 
 
 
 
79
  });
80
 
81
  writer.on("error", (err) => {
 
84
  });
85
 
86
  } catch (error) {
87
+ console.error("Download error:", error.message);
88
  return res.status(500).json({ error: "Failed to download file" });
89
  }
90
  });