-
Notifications
You must be signed in to change notification settings - Fork 722
/
util.js
473 lines (418 loc) · 11.7 KB
/
util.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
const url = require('url');
const FORMATS = require('./formats');
// Use these to help sort formats, higher is better.
const audioEncodingRanks = [
'mp4a',
'mp3',
'vorbis',
'aac',
'opus',
'flac',
];
const videoEncodingRanks = [
'mp4v',
'avc1',
'Sorenson H.283',
'MPEG-4 Visual',
'VP8',
'VP9',
'H.264',
];
const getBitrate = format => parseInt(format.bitrate) || 0;
const audioScore = format => {
const abitrate = format.audioBitrate || 0;
const aenc = audioEncodingRanks.findIndex(enc => format.codecs && format.codecs.includes(enc));
return abitrate + (aenc / 10);
};
/**
* Sort formats from highest quality to lowest.
* By resolution, then video bitrate, then audio bitrate.
*
* @param {Object} a
* @param {Object} b
* @returns {number}
*/
exports.sortFormats = (a, b) => {
const getResolution = format => {
const result = /(\d+)p/.exec(format.qualityLabel);
return result ? parseInt(result[1]) : 0;
};
const ares = getResolution(a);
const bres = getResolution(b);
const afeats = (~~!!ares * 2) + ~~!!a.audioBitrate;
const bfeats = (~~!!bres * 2) + ~~!!b.audioBitrate;
if (afeats === bfeats) {
if (ares === bres) {
let avbitrate = getBitrate(a);
let bvbitrate = getBitrate(b);
if (avbitrate === bvbitrate) {
let aascore = audioScore(a);
let bascore = audioScore(b);
if (aascore === bascore) {
const avenc = videoEncodingRanks.findIndex(enc => a.codecs && a.codecs.includes(enc));
const bvenc = videoEncodingRanks.findIndex(enc => b.codecs && b.codecs.includes(enc));
return bvenc - avenc;
} else {
return bascore - aascore;
}
} else {
return bvbitrate - avbitrate;
}
} else {
return bres - ares;
}
} else {
return bfeats - afeats;
}
};
/**
* Choose a format depending on the given options.
*
* @param {Array.<Object>} formats
* @param {Object} options
* @returns {Object}
* @throws {Error} when no format matches the filter/format rules
*/
exports.chooseFormat = (formats, options) => {
if (typeof options.format === 'object') {
if (!options.format.url) {
throw Error('Invalid format given, did you use `ytdl.getInfo()`?');
}
return options.format;
}
if (options.filter) {
formats = exports.filterFormats(formats, options.filter);
}
let format;
const quality = options.quality || 'highest';
switch (quality) {
case 'highest':
format = formats[0];
break;
case 'lowest':
format = formats[formats.length - 1];
break;
case 'highestaudio':
formats = exports.filterFormats(formats, 'audio');
sortFormatsSimple(formats, true);
format = formats[0];
break;
case 'lowestaudio':
formats = exports.filterFormats(formats, 'audio');
sortFormatsSimple(formats, true);
format = formats[formats.length - 1];
break;
case 'highestvideo':
formats = exports.filterFormats(formats, 'video');
sortFormatsSimple(formats);
format = formats[0];
break;
case 'lowestvideo':
formats = exports.filterFormats(formats, 'video');
sortFormatsSimple(formats);
format = formats[formats.length - 1];
break;
default:
format = getFormatByQuality(quality, formats);
break;
}
if (!format) {
throw Error(`No such format found: ${quality}`);
}
return format;
};
/**
* Gets a format based on quality or array of quality's
*
* @param {string|[string]} quality
* @param {[Object]} formats
* @returns {Object}
*/
const getFormatByQuality = (quality, formats) => {
let getFormat = itag => formats.find(format => `${format.itag}` === `${itag}`);
if (Array.isArray(quality)) {
return getFormat(quality.find(q => getFormat(q)));
} else {
return getFormat(quality);
}
};
/**
* Sort's the provided formats - highest bitrate first
*
* @param {[Object]} formats
* @param {boolean} audioOnly look at audio score instead of video bitrate
* @returns {[Object]}
*/
const sortFormatsSimple = (formats, audioOnly = false) => formats.sort((a, b) => {
if (audioOnly) return audioScore(b) - audioScore(a);
return getBitrate(b) - getBitrate(a);
});
/**
* @param {Array.<Object>} formats
* @param {Function} filter
* @returns {Array.<Object>}
*/
exports.filterFormats = (formats, filter) => {
let fn;
switch (filter) {
case 'videoandaudio':
case 'audioandvideo':
fn = format => format.hasVideo && format.hasAudio;
break;
case 'video':
fn = format => format.hasVideo;
break;
case 'videoonly':
fn = format => format.hasVideo && !format.hasAudio;
break;
case 'audio':
fn = format => format.hasAudio;
break;
case 'audioonly':
fn = format => !format.hasVideo && format.hasAudio;
break;
default:
if (typeof filter === 'function') {
fn = filter;
} else {
throw TypeError(`Given filter (${filter}) is not supported`);
}
}
return formats.filter(format => !!format.url && fn(format));
};
/**
* Extract string inbetween another.
*
* @param {string} haystack
* @param {string} left
* @param {string} right
* @returns {string}
*/
exports.between = (haystack, left, right) => {
let pos = haystack.indexOf(left);
if (pos === -1) { return ''; }
haystack = haystack.slice(pos + left.length);
pos = haystack.indexOf(right);
if (pos === -1) { return ''; }
haystack = haystack.slice(0, pos);
return haystack;
};
/**
* Get video ID.
*
* There are a few type of video URL formats.
* - https://www.youtube.com/watch?v=VIDEO_ID
* - https://m.youtube.com/watch?v=VIDEO_ID
* - https://youtu.be/VIDEO_ID
* - https://www.youtube.com/v/VIDEO_ID
* - https://www.youtube.com/embed/VIDEO_ID
* - https://music.youtube.com/watch?v=VIDEO_ID
* - https://gaming.youtube.com/watch?v=VIDEO_ID
*
* @param {string} link
* @return {string}
* @throws {Error} If unable to find a id
* @throws {TypeError} If videoid doesn't match specs
*/
const validQueryDomains = new Set([
'youtube.com',
'www.youtube.com',
'm.youtube.com',
'music.youtube.com',
'gaming.youtube.com',
]);
const validPathDomains = /^https?:\/\/(youtu\.be\/|(www\.)?youtube.com\/(embed|v)\/)/;
exports.getURLVideoID = link => {
const parsed = url.parse(link, true);
let id = parsed.query.v;
if (validPathDomains.test(link) && !id) {
const paths = parsed.pathname.split('/');
id = paths[paths.length - 1];
} else if (parsed.hostname && !validQueryDomains.has(parsed.hostname)) {
throw Error('Not a YouTube domain');
}
if (!id) {
throw Error(`No video id found: ${link}`);
}
id = id.substring(0, 11);
if (!exports.validateID(id)) {
throw TypeError(`Video id (${id}) does not match expected ` +
`format (${idRegex.toString()})`);
}
return id;
};
/**
* Gets video ID either from a url or by checking if the given string
* matches the video ID format.
*
* @param {string} str
* @returns {string}
* @throws {Error} If unable to find a id
* @throws {TypeError} If videoid doesn't match specs
*/
exports.getVideoID = str => {
if (exports.validateID(str)) {
return str;
} else {
return exports.getURLVideoID(str);
}
};
/**
* Returns true if given id satifies YouTube's id format.
*
* @param {string} id
* @return {boolean}
*/
const idRegex = /^[a-zA-Z0-9-_]{11}$/;
exports.validateID = id => idRegex.test(id);
/**
* Checks wether the input string includes a valid id.
*
* @param {string} string
* @returns {boolean}
*/
exports.validateURL = string => {
try {
exports.getURLVideoID(string);
return true;
} catch (e) {
return false;
}
};
/**
* @param {Object} format
* @returns {Object}
*/
exports.addFormatMeta = format => {
format = Object.assign({}, FORMATS[format.itag], format);
format.hasVideo = !!format.qualityLabel;
format.hasAudio = !!format.audioBitrate;
format.container = format.mimeType ?
format.mimeType.split(';')[0].split('/')[1] : null;
format.codecs = format.mimeType ?
exports.between(format.mimeType, 'codecs="', '"') : null;
format.videoCodec = format.hasVideo && format.codecs ?
format.codecs.split(', ')[0] : null;
format.audioCodec = format.hasAudio && format.codecs ?
format.codecs.split(', ').slice(-1)[0] : null;
format.isLive = /\/source\/yt_live_broadcast\//.test(format.url);
// TODO: Remove these warnings later and remove the properties.
// Remember to remove from typings too.
exports.deprecate(format, 'live', format.isLive, 'format.live', 'format.isLive');
format.isHLS = /\/manifest\/hls_(variant|playlist)\//.test(format.url);
format.isDashMPD = /\/manifest\/dash\//.test(format.url);
return format;
};
/**
* Get only the string from an HTML string.
*
* @param {string} html
* @returns {string}
*/
exports.stripHTML = html => html
.replace(/[\n\r]/g, ' ')
.replace(/\s*<\s*br\s*\/?\s*>\s*/gi, '\n')
.replace(/<\s*\/\s*p\s*>\s*<\s*p[^>]*>/gi, '\n')
.replace(/<a\s+(?:[^>]*?\s+)?href=(?:["'])\/redirect.*?q=(.*?)(?:[&'"]).*?<\/a>/gi,
(_, p1) => decodeURIComponent(p1))
.replace(/<a\s+(?:[^>]*?\s+)?href=(?:["'])((?:https?|\/).*?)(?:['"]).*?<\/a>/gi,
(_, p1) => url.resolve('https://youtube.com/', p1))
.replace(/<.*?>/gi, '')
.trim();
/**
* Get a number from an abbreviated number string.
*
* @param {string} string
* @returns {number}
*/
exports.parseAbbreviatedNumber = string => {
const match = string
.replace(',', '.')
.replace(' ', '')
.match(/([\d,.]+)([MK]?)/);
if (match) {
let [, num, multi] = match;
num = parseFloat(num);
return multi === 'M' ? num * 1000000 :
multi === 'K' ? num * 1000 : num;
}
return null;
};
/**
* Match begin and end braces of input JSON, return only json
*
* @param {string} mixedJson
* @returns {string}
*/
exports.cutAfterJSON = mixedJson => {
let open, close;
if (mixedJson[0] === '[') {
open = '[';
close = ']';
} else if (mixedJson[0] === '{') {
open = '{';
close = '}';
}
if (!open) {
throw new Error(`Can't cut unsupported JSON (need to begin with [ or { ) but got: ${mixedJson[0]}`);
}
// States if the loop is currently in a string
let isString = false;
// Current open brackets to be closed
let counter = 0;
let i;
for (i = 0; i < mixedJson.length; i++) {
// Toggle the isString boolean when leaving/entering string
if (mixedJson[i] === '"' && mixedJson[i - 1] !== '\\') {
isString = !isString;
continue;
}
if (isString) continue;
if (mixedJson[i] === open) {
counter++;
} else if (mixedJson[i] === close) {
counter--;
}
// All brackets have been closed, thus end of JSON is reached
if (counter === 0) {
// Return the cut JSON
return mixedJson.substr(0, i + 1);
}
}
// We ran through the whole string and ended up with an unclosed bracket
throw Error("Can't cut unsupported JSON (no matching closing bracket found)");
};
/**
* Checks if there is a playability error.
*
* @param {Object} info
* @param {string} status
* @returns {!Error}
*/
exports.playError = (info, status) => {
let playability = info.playerResponse.playabilityStatus;
if (playability && playability.status === status) {
return Error(playability.reason || (playability.messages && playability.messages[0]));
}
return null;
};
/**
* Temporary helper to help deprecating a few properties.
*
* @param {Object} obj
* @param {string} prop
* @param {Object} value
* @param {string} oldPath
* @param {string} newPath
*/
exports.deprecate = (obj, prop, value, oldPath, newPath) => {
Object.defineProperty(obj, prop, {
get: () => {
// eslint-disable-next-line no-console
console.warn(
`\`${oldPath}\` will be removed in a near future release, ` +
`use \`${newPath}\` instead.`);
return value;
},
});
};