-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
102 lines (90 loc) · 2.83 KB
/
index.js
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import cors from "cors";
import express from "express";
import ffmpeg from "fluent-ffmpeg";
import fs from "fs";
import path from "path";
import youtubeDl from "youtube-dl-exec";
import { dirname } from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
const port = 3000;
app.use(cors("*"));
app.get("/", (req, res) => {
res.send("Welcome to my server!");
console.log(req);
console.log(res);
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
app.get("/download/mp4", async (req, res) => {
console.log("Download started as mp4");
const URL = req.query.URL;
const name = req.query.name;
console.log(URL);
console.log(name);
try {
const output = await youtubeDl(URL, {
format: "mp4",
output: `${name}.mp4`,
noCheckCertificates: true,
noWarnings: true,
preferFreeFormats: true,
addHeader: ["referer:youtube.com", "user-agent:googlebot"],
});
console.log("Download finished as mp4");
// Send the downloaded video as mp4 to the client
const filePath = path.join(__dirname, `${name}.mp4`);
res.download(filePath, (err) => {
if (err) {
console.error("Error during file sending:", err);
res.status(500).json({ success: false, error: "File sending failed" });
} else {
fs.unlinkSync(filePath); // delete the file after sending it
}
});
} catch (error) {
console.error("Error during download:", error);
res.status(500).json({ success: false, error: "Download failed" });
}
});
app.get("/download/mp3", async (req, res) => {
console.log("Download started as mp3");
const URL = req.query.URL;
const name = req.query.name;
console.log(URL);
console.log(name);
try {
const output = await youtubeDl(URL, {
format: "bestaudio",
output: `${name}_conversion.mp3`,
noCheckCertificates: true,
noWarnings: true,
preferFreeFormats: true,
addHeader: ["referer:youtube.com", "user-agent:googlebot"],
});
console.log("Download finished as mp3");
ffmpeg(`${name}_conversion.mp3`)
.output(`${name}.mp3`)
.on("end", function () {
console.log("conversion ended");
const filePath = path.join(__dirname, `${name}.mp3`);
res.download(filePath, (err) => {
if (err) {
console.error("Error during file sending:", err);
res
.status(500)
.json({ success: false, error: "File sending failed" });
} else {
fs.unlinkSync(filePath); // delete the file after sending it
}
});
})
.run();
} catch (error) {
console.error("Error during download:", error);
res.status(500).json({ success: false, error: "Download failed" });
}
});