-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
258 lines (225 loc) · 7.33 KB
/
server.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
"use strict";
const path = require("path");
const child_process = require("child_process");
const fs = require("fs");
const express = require("express");
const expressCookieParser = require("cookie-parser");
const app = express();
app.use(expressCookieParser());
const PORT = 8093;
// /checkpsw?psw=... (the param is uri encoded, is the SHA256-hashed password)
// return 200 if correct psw, 401 if it isn't, 500 otherwise
app.get("/api/checkpsw", async (req, res) => {
let userPsw = decodeURIComponent(req.query.psw);
const clientIp = req.headers["x-forwarded-for"] || req.socket.remoteAddress;
try {
(await checkPsw(userPsw)) ? res.sendStatus(200) : res.sendStatus(401); //the replace remove all whitespaces and new lines
} catch (ex) {
logString("\tERR:", ex, "from", clientIp, "(", reqToString(req), ")");
res.sendStatus(500);
}
});
// /isvalid?url=... (the param is uri encoded)
// return 200 if is a valid youtube-dl url, 404 if youtube-dl can't find the video, 500 otherwise
app.get("/api/isvalid", async (req, res) => {
let videoUrl = decodeURIComponent(req.query.url).replace(/\s/g, "");
const clientIp = req.headers["x-forwarded-for"] || req.socket.remoteAddress;
let result;
try {
if (!await checkPsw(req.cookies.psw)) {
res.sendStatus(401);
return;
}
result = await checkValidUrl(videoUrl);
res.sendStatus(result);
} catch (ex) {
logString("\tERR:", ex, "from", clientIp, "(", reqToString(req), ")");
res.sendStatus(500);
return;
}
});
// /getvideo?url=... (the param is uri encoded)
// return the requested video (mp4)
app.get("/api/getvideo", async (req, res) => {
let videoUrl = decodeURIComponent(req.query.url).replace(/\s/g, "");
const clientIp = req.headers["x-forwarded-for"] || req.socket.remoteAddress;
logString(`requested VIDEO from ${clientIp} :\t${videoUrl}`);
let filePath;
try {
if (!await checkPsw(req.cookies.psw)) {
//res.sendStatus(401);
//return;
}
filePath = await downloadVideo(videoUrl);
} catch (ex) {
logString("\tERR:", ex, "from", clientIp, "(", reqToString(req), ")");
if (ex == "ERROR: Video unavailable")
res.sendStatus(404);
else
res.sendStatus(500);
return;
}
if (filePath)
res.download(filePath);
else
res.sendStatus(500);
res.on("close", () => {
try {
if (filePath)
fs.unlinkSync(filePath); // deletes the file after sending it to the client
} catch (ex) {
console.log("ERR: deleting file", filePath, ":", ex);
}
});
});
// /getaudio?url=... (the param is uri encoded)
// return the requested audio track of the video (mp3)
app.get("/api/getaudio", async (req, res) => {
let videoUrl = decodeURIComponent(req.query.url).replace(/\s/g, "");
const clientIp = req.headers["x-forwarded-for"] || req.socket.remoteAddress;
logString(`requested AUDIO from ${clientIp} :\t${videoUrl}`);
let filePath;
try {
if (!await checkPsw(req.cookies.psw)) {
res.sendStatus(401);
return;
}
filePath = await downloadAudio(videoUrl);
} catch (ex) {
logString("\tERR:", ex, "from", clientIp, "(", reqToString(req), ")");
if (ex == "ERROR: Video unavailable") {
res.sendStatus(404);
}
else {
res.sendStatus(500);
}
return;
}
if (filePath)
res.download(filePath);
else
res.sendStatus(500);
res.on("close", () => {
try {
if (filePath)
fs.unlinkSync(filePath); // deletes the file after sending it to the client
} catch (ex) {
logString("ERR: deleting file", filePath, ":", ex);
}
});
});
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
app.use(express.static("public"));
// cleans the downloads folder
child_process.exec("rm -r downloads; mkdir downloads", (err, stdout, stderr) => {
if (stderr) {
console.log("stdERR:", stderr);
return;
}
if (err) {
console.log(err);
return;
}
console.log();
app.listen(PORT, () => {
logString("Listening on", PORT);
}).on("error", () => {
app.listen(PORT + 1);
logString("Port", PORT, "already in use, listening on", PORT + 1);
});
// test:
// console.log(encodeURIComponent("https://www.youtube.com/watch?v=ThAACSvrvdQ"))
});
// ========== methods ==========
async function checkPsw(userPsw) {
return new Promise((resolve, reject) => {
fs.readFile("hashedpassword.txt", "utf-8", (err, data) => {
if (err) reject(err);
resolve(userPsw == data.replace(/\v|\s/gm, "")); //the replace removes all whitespaces and new lines
});
});
}
async function checkValidUrl(videoUrl) {
// returns 404 for invalid url, 200 otherwise
return new Promise((resolve) => {
child_process.exec(`youtube-dl -e "${videoUrl}"`, (err, stdout, stderr) => {
if (stderr) {
resolve(404);
return;
}
if (err) {
resolve(404);
return;
}
resolve(200);
});
});
}
async function downloadVideo(videoUrl) {
return new Promise((resolve, reject) => {
child_process.exec(`cd downloads && youtube-dl --format mp4 "${videoUrl}"`, (err, stdout, stderr) => {
if (stderr) {
reject(stderr.replace("\n", ""));
return;
}
if (err) {
//console.log(err);
reject(err);
return;
}
let filename = stdout.match(/^\[ffmpeg\] Destination: (.+)$/m);
if (!filename) // file wasn't converted?
filename = stdout.match(/^\[download\] Destination: (.+)$/m);
if (!filename) // file already present
filename = stdout.match(/^\[download\] (.+) has already been downloaded$/m);
filename = filename[1]; //[0] is the entire match, [1] the 1st group
resolve(path.join(__dirname, "downloads", filename));
});
});
}
async function downloadAudio(videoUrl) {
return new Promise((resolve, reject) => {
child_process.exec(`cd downloads && youtube-dl -x --audio-format mp3 "${videoUrl}"`, (err, stdout, stderr) => {
if (stderr) {
reject(stderr.replace("\n", ""));
return;
}
if (err) {
//console.log(err);
reject(err);
return;
}
let filename = stdout.match(/^\[ffmpeg\] Destination: (.+)$/m);
if (!filename) // file wasn't converted?
filename = stdout.match(/^\[download\] Destination: (.+)$/m);
if (!filename) // file already present
filename = stdout.match(/^\[download\] (.+) has already been downloaded$/m);
filename = filename[1]; //[0] is the entire match, [1] the 1st group
resolve(path.join(__dirname, "downloads", filename));
});
});
}
function logString(...msgs) {
let d = new Date();
let finalString = `${("" + d.getDate()).padStart(2, "0")}/${(d.getMonth() + 1 + "").padStart(2, "0")}/${d.getFullYear()} ${("" + d.getHours()).padStart(2, "0")}:${("" + d.getMinutes()).padStart(2, "0")}:${("" + d.getSeconds()).padStart(2, "0")} - ${msgs.join(" ")}`;
console.log(finalString);
}
function reqToString(req) {
return JSON.stringify({
// headers: req.headers,
method: req.method,
url: req.url,
httpVersion: req.httpVersion,
body: req.body,
// cookies: req.cookies,
// path: req.path,
// protocol: req.protocol,
query: req.query,
hostname: req.hostname,
ip: req.headers["x-forwarded-for"] || req.socket.remoteAddress,
originalUrl: req.originalUrl,
params: req.params,
}, null, 2);
}