This repository has been archived by the owner on Feb 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
290 lines (269 loc) · 8.34 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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// Import vital settings
require('dotenv').config();
const BYTE_LIMIT = Number(process.env.BYTE_LIMIT || Infinity);
const TIME_LIMIT = Number(process.env.TIME_LIMIT || Infinity);
const PORT = process.env.PORT || 8080;
const URL = process.env.URL || `http://localhost:${PORT}/`;
const PRODUCTION_MODE = process.env.NODE_ENV === 'production';
const DEFAULTS = require('./settings');
const RAPID_FORKS = Number(process.env.RAPID_FORKS || 1);
// Import dependencies
const express = require('express');
const ytdl = require('ytdl-core');
const ytpl = require('ytpl');
const request = require('request');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const csurf = require('csurf');
const formats = require('ytdl-core/lib/formats');
// Import external dependencies
const secure = require('./lib/encrypt');
const app = express();
const CSRF = csurf({
cookie: {
secure: PRODUCTION_MODE,
httpOnly: PRODUCTION_MODE,
}
});
app.use(bodyParser.json());
app.use(cookieParser());
if (!process.env.HIVE_QUEEN) {
app.use(express.static(__dirname + '/public'));
}
app.get('/', CSRF, (req, res) => {
res.cookie('XSRF-TOKEN', req.csrfToken());
res.set({
'X-Frame-Options': 'DENY',
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
});
res.status(302).sendFile(__dirname + '/index.html');
});
function slice(arr, target) {
return arr.slice(0, arr.indexOf(target) + 1);
}
function findOptimal(info, type, quality, format, convert) {
const remaining = slice(DEFAULTS[type].qualityList, quality);
let optimal =
ytdl.filterFormats(info.formats, `${type}only`)
.filter(i => (convert ? true : i.container === format) && remaining.includes(i[DEFAULTS[type].target]))
.filter(b => !b.mimeType.includes('av01'))
.sort((a, b) => type === 'video' ? b.bitrate - a.bitrate : b.audioBitrate - a.audioBitrate)[0];
if (!optimal) {
throw 'There are no sources available with those settings!';
}
optimal.contentLength = Number(optimal.contentLength);
if (optimal.contentLength > BYTE_LIMIT) {
throw 'Video is too large! Use a lower quality.';
}
return {
format: optimal.container,
quality: optimal[DEFAULTS[type].target],
source: secure.encrypt(JSON.stringify({
url: optimal.url,
contentLength: optimal.contentLength
})),
length: optimal.contentLength,
segments: optimal.segments
}
}
app.post('/playlist', CSRF, async (req, res) => {
if (req.header('Referer') !== URL) {
return res.status(403).json({
error: 'Illegal Request (Incorrect Referer).'
});
}
const {playlist} = req.body;
const response = {error: null};
const Err = (code, str) => {
response.error = str;
res.status(code).json(response);
}
try {
response.urls = await ytpl(playlist, {limit: Infinity, pages: Infinity}).then(data => data.items.map(i => i.shortUrl));
res.status(302).json(response);
} catch(e) {
console.log(e);
Err(403, 'Unable to fetch playlist.');
}
});
app.post('/download', CSRF, async (req, res) => {
if (req.header('Referer') !== URL) {
return res.status(403).json({
error: 'Illegal Request (Incorrect Referer).'
});
}
const {type, metadata, segments} = req.body;
const response = {error: null};
const Err = (code, str) => {
response.error = str;
res.status(code).json(response);
}
if (type !== 'video' && type !== 'audio') {
return Err(500, 'Invalid type.');
}
if (!metadata) {
return Err(403, 'Missing data.');
}
try {
const {url, contentLength} = JSON.parse(await secure.decrypt(metadata));
if (segments) {
return rapidSegmentDownload(url, segments).then(buffer => {
res.status(302).send(buffer);
});
}
if (RAPID_FORKS === 1) {
request(url).pipe(res.status(302));
} else {
rapidDownload(url, contentLength).then(buffer => {
res.status(302).send(buffer)
});
}
} catch(e) {
console.log(e);
Err(403, 'Unable to download request.');
}
});
app.post('/meta', CSRF, (req, res) => {
if (req.header('Referer') !== URL) {
return res.status(403).json({
error: 'Illegal Request (Incorrect Referer).'
});
}
let {link, type, videoQuality, audioQuality, videoFormat, audioFormat, convert} = req.body;
if (audioQuality) audioQuality = Number(audioQuality);
const response = {error: null};
const Err = (str) => {
console.log(str);
response.error = str;
res.status(302).json(response);
}
if (type !== 'video' && type !== 'audio') {
return Err('Invalid type.');
}
if (!(/(?<=^|(https?:\/\/(youtu\.be\/|(www\.)?youtube\.com\/watch\?v=)))[A-Za-z0-9_-]{11}(?=$|&)/g).test(link)) {
return Err('Unable to detect video.');
}
if (type === 'video') {
if (!DEFAULTS.video.qualityList.includes(videoQuality) || !DEFAULTS.video.formatList.includes(videoFormat)) {
return Err('Invalid video arguments.');
}
audioFormat = videoFormat;
}
if (!DEFAULTS.audio.qualityList.includes(audioQuality) || !DEFAULTS.audio.formatList.includes(audioFormat)) {
return Err('Invalid audio arguments.');
}
ytdl.getInfo(link)
.then(async info => {
console.log(info);
response.title = info.player_response.videoDetails.title;
let manifests = new Set(info.formats.filter(i => i.url.indexOf('https://manifest') === 0).map(i => i.url));
if (manifests.size > 0) {
let addedFormats = [];
for (let manifest of manifests.entries()) {
addedFormats.push(await parseManifest(manifest[0]));
}
info.formats = info.formats.filter(i => i.url.indexOf('https://manifest') !== 0).concat(addedFormats.flat());
}
let seconds = Number(info.length_seconds);
if (seconds > TIME_LIMIT) {
return Err('Video is too long! Choose a different video.');
}
try {
if (type === 'video') {
const optimal = findOptimal(info, 'video', videoQuality, videoFormat, convert);
response.video = await optimal.source;
response.videoQuality = optimal.quality;
response.videoFormat = optimal.format;
response.videoLength = optimal.length;
response.videoSegments = optimal.segments;
}
const optimal = findOptimal(info, 'audio', audioQuality, audioFormat, convert);
response.audio = await optimal.source;
response.audioQuality = optimal.quality;
response.audioFormat = optimal.format;
response.audioLength = optimal.length;
response.audioSegments = optimal.segments;
console.log(response);
res.status(302).json(response);
} catch (e) {
console.log(e);
Err(e.message || e);
}
}).catch(err => {
if (err) {
console.log(err);
return Err('Unable to find video.');
}
});
});
app.use((err, req, res, next) => {
if (err.code !== 'EBADCSRFTOKEN') return next();
res.status(403).json({error: 'Invalid CSRF Token!'});
});
function partialDownload(url, start, end) {
return new Promise(resolve => {
request({
url: url,
headers: {
range: `bytes=${start}-${end}`
},
encoding: null
}, async (err, res, body) => {
if (err) resolve(await partialDownload(url, start, end));
else resolve(res.body);
});
});
}
async function rapidDownload(url, length) {
const MAX = RAPID_FORKS;
length = Number(length);
let div = Math.trunc(length / MAX);
let requests = [];
let i;
for (i = 0; i < MAX - 1; ++i) {
requests.push(partialDownload(url, i*div, (i+1)*div-1));
}
requests.push(partialDownload(url, i*div, length));
let final = await Promise.all(requests);
return Buffer.concat(final.flat());
}
function downloadSegment(url) {
return new Promise(resolve => {
request({
url,
encoding: null
}, async (err, req, body) => {
if (err) return resolve(await downloadSegment(url));
resolve(req.body);
});
});
}
async function rapidSegmentDownload(baseURL, segments) {
let requests = [];
segments.forEach(seg => {
requests.push(downloadSegment(`${baseURL}${seg}`));
});
let final = await Promise.all(requests);
return Buffer.concat(final);
}
function parseManifest(url) {
return new Promise((resolve, reject) => {
request(url, (err, res, body) => {
if (err) reject(err);
else resolve(Array.from(res.body.match(/(?<=<Representation).*?(?=\/Representation>)/g)).map(i => {
let format = Object.assign({
segments: Array.from(i.match(/<SegmentList>.*?<\/SegmentList>/g)[0].match(/(?<=(sourceURL|media)=\").*?(?=\")/g)),
url: i.match(/(?<=\<BaseURL\>).*?(?=\<\/BaseURL\>)/g)[0],
}, formats[i.match(/(?<=id=").*?(?=")/g)[0]]);
format.container = format.mimeType.match(/(?<=\/).*?(?=;)/g)[0];
format.raw = i;
return format;
}));
});
});
}
app.listen(PORT, () => {
console.log('ACTIVE', PORT);
});