-
Notifications
You must be signed in to change notification settings - Fork 818
/
Copy pathdownload-test.js
755 lines (683 loc) · 24.1 KB
/
download-test.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
const assert = require('assert');
const path = require('path');
const fs = require('fs');
const streamEqual = require('stream-equal');
const sinon = require('sinon');
const nock = require('./nock');
const ytdl = require('..');
const net = require('net');
describe('Download video', () => {
const filter = format => format.container === 'mp4';
let expectedInfo;
before(() => expectedInfo = require('./files/videos/regular/expected-info.json'));
let clock;
before(() => { clock = sinon.useFakeTimers({ toFake: ['setTimeout'] }); });
after(() => { clock.restore(); });
it('Should be pipeable and data equal to stored file', async() => {
const id = '_HSylqgVYQI';
const scope = nock(id, 'regular', {
watchJson: false,
});
const stream = ytdl(id, { filter: filter });
const video = path.resolve(__dirname, `files/videos/regular/video.flv`);
stream.on('info', (info, format) => {
scope.urlReplyWithFile(format.url, 200, video);
});
const filestream = fs.createReadStream(video);
let equal = await streamEqual(filestream, stream);
scope.done();
assert.ok(equal);
});
describe('When there is an error', () => {
it('Stream emits an error', done => {
const id = '99999999999';
const scope = nock(id, 'non-existent');
const stream = ytdl(id, { filter, requestOptions: { maxRetries: 0 } });
stream.on('error', err => {
assert.ok(err);
assert.strictEqual(err.message, 'Video unavailable');
scope.done();
done();
});
});
});
describe('destroy stream', () => {
describe('immediately', () => {
it('Doesn\'t start the download', done => {
const id = '_HSylqgVYQI';
const scope = nock(id, 'regular', {
watchJson: false,
});
const stream = ytdl(id, { filter });
stream.destroy();
stream.on('request', () => {
done(Error('Should not emit `request`'));
});
stream.on('response', () => {
done(Error('Should not emit `response`'));
});
stream.on('info', () => {
scope.done();
done();
});
});
});
describe('right after request is made', () => {
it('Doesn\'t start the download', done => {
const id = '_HSylqgVYQI';
const scope = nock(id, 'regular', {
watchJson: false,
});
const stream = ytdl(id, { filter });
stream.on('request', () => {
stream.destroy();
scope.done();
done();
});
stream.on('info', (info, format) => {
nock.url(format.url).reply(200, 'aaaaaaaaaaaa');
});
stream.on('response', () => {
done(Error('Should not emit `response`'));
});
stream.on('data', () => {
done(Error('Should not emit `data`'));
});
stream.on('error', err => {
// Swallow possible error, only occurs in node v10, v12.
assert.strictEqual(err.message, 'socket hang up');
});
});
});
describe('after download has started', () => {
it('Download is incomplete', done => {
const id = '_HSylqgVYQI';
const scope = nock(id, 'regular', {
watchJson: false,
});
const stream = ytdl(id, { filter });
const video = path.resolve(__dirname, `files/videos/regular/video.flv`);
stream.on('info', (info, format) => {
scope.urlReplyWithFile(format.url, 200, video);
});
stream.on('response', res => {
res.on('data', () => {
done(Error('Should not emit `data`'));
});
stream.destroy();
scope.done();
done();
});
stream.on('abort', () => {
done(Error('Should not emit `abort`'));
});
});
});
});
describe('destroy chunked stream', () => {
const chunkedFilter = 'videoonly';
describe('immediately', () => {
it('Doesn\'t start the download', done => {
const id = '_HSylqgVYQI';
const scope = nock(id, 'regular', {
watchJson: false,
});
const stream = ytdl(id, { filter: chunkedFilter });
stream.destroy();
stream.on('request', () => {
done(Error('Should not emit `request`'));
});
stream.on('response', () => {
done(Error('Should not emit `response`'));
});
stream.on('info', () => {
scope.done();
done();
});
});
});
describe('right after request is made', () => {
it('Doesn\'t start the download', done => {
const id = '_HSylqgVYQI';
const scope = nock(id, 'regular', {
watchJson: false,
});
const stream = ytdl(id, { filter: chunkedFilter });
stream.on('request', () => {
stream.destroy();
scope.done();
done();
});
stream.on('info', (info, format) => {
nock.url(format.url).reply(200, 'aaaaaaaaaaaa');
});
stream.on('response', () => {
done(Error('Should not emit `response`'));
});
stream.on('data', () => {
done(Error('Should not emit `data`'));
});
const abort = sinon.spy();
stream.on('abort', abort);
stream.on('error', err => {
// Swallow possible error, only occurs in node v10, v12.
assert.strictEqual(err.message, 'socket hang up');
});
});
});
describe('after download has started', () => {
it('Download is incomplete', done => {
const id = '_HSylqgVYQI';
const scope = nock(id, 'regular', {
watchJson: false,
});
const stream = ytdl(id, { filter: chunkedFilter });
const video = path.resolve(__dirname, `files/videos/regular/video.flv`);
stream.on('info', (info, format) => {
scope.urlReplyWithFile(format.url, 200, video);
});
stream.on('response', res => {
res.on('data', () => {
done(Error('Should not emit `data`'));
});
stream.destroy();
scope.done();
done();
});
stream.on('abort', () => {
done(Error('Should not emit `abort`'));
});
});
});
});
describe('stream disconnects before end', () => {
const id = '_HSylqgVYQI';
const video = path.resolve(__dirname, `files/videos/regular/video.flv`);
let filesize;
before(done => {
fs.stat(video, (err, stat) => {
assert.ifError(err);
filesize = stat.size;
done();
});
});
const destroy = (req, res) => {
req.destroy();
res.unpipe();
};
it('Still downloads the whole video', async() => {
const scope = nock(id, 'regular', {
watchJson: false,
});
const stream = ytdl(id);
let destroyedTimes = 0;
stream.on('info', (info, format) => {
let req, res;
stream.once('request', a => { req = a; });
stream.once('response', a => { res = a; });
stream.on('reconnect', () => { clock.tick(500); });
scope.urlReplyWithFile(format.url, 200, video, {
'content-length': filesize,
'accept-ranges': 'bytes',
});
stream.on('progress', (chunkLength, downloaded, total) => {
if (downloaded / total >= 0.5) {
scope.urlReply(format.url, 206, () => fs.createReadStream(video, { start: downloaded }), {
'content-range': `bytes=${downloaded}-${filesize}/${filesize}`,
'content-length': filesize - downloaded,
'accept-ranges': 'bytes',
});
stream.removeAllListeners('progress');
destroyedTimes++;
destroy(req, res);
}
});
});
const filestream = fs.createReadStream(video);
let equal = await streamEqual(filestream, stream);
scope.done();
assert.strictEqual(destroyedTimes, 1);
assert.ok(equal);
});
describe('with range', () => {
it('Downloads from the given `start` to `end`', async() => {
const scope = nock(id, 'regular', {
watchJson: false,
});
const start = Math.floor(filesize * 0.1);
const end = Math.floor(filesize * 0.45);
const rangedSize = end - start + 1;
const stream = ytdl(id, { range: { start, end } });
let destroyedTimes = 0;
stream.on('info', (info, format) => {
let req, res;
stream.on('request', a => { req = a; });
stream.on('response', a => { res = a; });
stream.on('reconnect', () => { clock.tick(500); });
scope.urlReply(format.url, 206, () => fs.createReadStream(video, { start, end }), {
'content-range': `bytes=${start}-${end}/${filesize}`,
'content-length': rangedSize,
'accept-ranges': 'bytes',
});
stream.on('progress', (chunkLength, downloaded, total) => {
if (downloaded / total >= 0.5) {
scope.urlReply(format.url, 206, () => fs.createReadStream(video, { start: start + downloaded, end }), {
'content-range': `bytes=${downloaded}-${end}/${filesize}`,
'content-length': rangedSize - downloaded,
'accept-ranges': 'bytes',
});
destroyedTimes++;
stream.removeAllListeners('progress');
destroy(req, res);
}
});
});
const filestream = fs.createReadStream(video, { start, end });
let equal = await streamEqual(filestream, stream);
scope.done();
assert.strictEqual(destroyedTimes, 1);
assert.ok(equal);
});
});
describe('that should be chunked', () => {
it('Starts downloading video successfully and data equal to stored file', async() => {
const scope = nock(id, 'regular', {
watchJson: false,
});
const dlChunkSize = 1024 * 200;
const stream = ytdl(id, { filter: 'videoonly', dlChunkSize });
stream.on('info', (info, format) => {
scope.urlReply(format.url, 206, () => fs.createReadStream(video, { start: 0, end: dlChunkSize - 1 }), {
'content-range': `bytes=0-${dlChunkSize - 1}/${filesize}`,
'content-length': dlChunkSize,
'accept-ranges': 'bytes',
});
stream.on('progress', (chunk, downloaded) => {
if (downloaded % dlChunkSize === 0) {
scope.urlReply(
format.url,
206,
() => fs.createReadStream(video, { start: dlChunkSize, end: filesize - 1 }),
{
'content-range': `bytes=${dlChunkSize}-${filesize - 1}/${filesize}`,
'content-length': filesize - downloaded,
'accept-ranges': 'bytes',
});
stream.removeAllListeners('progress');
}
});
});
const filestream = fs.createReadStream(video);
let equal = await streamEqual(filestream, stream);
scope.done();
assert.ok(equal);
});
});
describe('chunked with range', () => {
it('Downloads from the given `start` to `end`', async() => {
const scope = nock(id, 'regular', {
watchJson: false,
});
const start = Math.floor(filesize * 0.1);
const end = Math.floor(filesize * 0.15);
const rangedSize = end - start + 1;
const dlChunkSize = 1024 * 10;
const stream = ytdl(id, { filter: 'videoonly', dlChunkSize, range: { start, end } });
let totalBytes, downloadedBytes, reqStart, reqEnd = 0;
stream.on('request', req => {
const range = req.options.headers.range.replace('bytes=', '').split('-');
reqStart = reqStart !== start ? parseInt(range[0]) : reqStart;
reqEnd = parseInt(range[1]);
});
stream.on('info', (info, format) => {
let chunkStart = start;
let chunkEnd = rangedSize < dlChunkSize ? end : start + dlChunkSize - 1;
let contentLength = chunkEnd - chunkStart + 1;
scope.urlReply(format.url, 206, () => fs.createReadStream(video, { start: chunkStart, end: chunkEnd }), {
'content-range': `bytes=${chunkStart}-${chunkEnd}/${rangedSize}`,
'content-length': contentLength,
'accept-ranges': 'bytes',
});
stream.on('progress', (chunk, downloaded, total) => {
if (downloaded % dlChunkSize === 0 && chunkEnd !== end) {
chunkStart = chunkEnd + 1;
chunkEnd = rangedSize - downloaded < dlChunkSize ? end : chunkEnd + dlChunkSize;
contentLength = chunkEnd ? chunkEnd - chunkStart + 1 : end - chunkStart;
scope.urlReply(
format.url,
206,
() => fs.createReadStream(video, { start: chunkStart, end: chunkEnd }),
{
'content-range': `bytes=${chunkStart}-${chunkEnd}/${rangedSize}`,
'content-length': contentLength,
'accept-ranges': 'bytes',
});
}
totalBytes = total;
downloadedBytes = downloaded;
});
});
const filestream = fs.createReadStream(video, { start, end });
let equal = await streamEqual(filestream, stream);
scope.done();
assert.ok(equal);
assert.strictEqual(totalBytes, rangedSize);
assert.strictEqual(downloadedBytes, totalBytes);
assert.strictEqual(reqStart, start);
assert.strictEqual(reqEnd, end);
});
});
it('Chunks video only and chunk size matches given size', done => {
const dlChunkSize = 1024 * 200;
const stream = ytdl.downloadFromInfo(expectedInfo, { filter: 'videoonly', dlChunkSize });
stream.on('info', (info, format) => {
nock.url(format.url)
.reply(206);
});
stream.on('request', req => {
const reqChunkSize = parseInt(req.options.headers.range.split('-')[1]);
assert.strictEqual(reqChunkSize, dlChunkSize);
stream.removeAllListeners('request');
stream.destroy();
done();
});
});
it('Chunks audio only and chunk size matches given size', done => {
const dlChunkSize = 1024;
const stream = ytdl.downloadFromInfo(expectedInfo, { filter: 'audioonly', dlChunkSize });
stream.on('info', (info, format) => {
nock.url(format.url)
.reply(206);
});
stream.on('request', req => {
const reqChunkSize = parseInt(req.options.headers.range.split('-')[1]);
assert.strictEqual(reqChunkSize, dlChunkSize);
stream.removeAllListeners('request');
stream.destroy();
done();
});
});
});
describe('with start range', () => {
it('Range added to download headers', done => {
const start = 500;
const stream = ytdl.downloadFromInfo(expectedInfo, {
range: { start },
});
stream.on('info', (info, format) => {
nock.url(format.url)
.reply(206);
});
stream.resume();
stream.on('error', done);
stream.on('request', req => {
const reqStart = parseInt(req.options.headers.range.replace('bytes=', '').split('-')[0]);
assert.strictEqual(reqStart, start);
done();
});
});
});
describe('chunked with start range', () => {
it('Range added to download headers', done => {
const start = 500;
const stream = ytdl.downloadFromInfo(expectedInfo, {
filter: 'audioonly',
range: { start },
});
stream.on('info', (info, format) => {
nock.url(format.url)
.reply(206);
});
stream.resume();
stream.on('error', done);
stream.on('request', req => {
const reqStart = parseInt(req.options.headers.range.replace('bytes=', '').split('-')[0]);
assert.strictEqual(reqStart, start);
done();
});
});
});
describe('with end range', () => {
it('Range added to download headers', done => {
const end = 1000;
const stream = ytdl.downloadFromInfo(expectedInfo, {
range: { end },
});
stream.on('info', (info, format) => {
nock.url(format.url)
.reply(206);
});
stream.resume();
stream.on('error', done);
stream.on('request', req => {
const reqEnd = parseInt(req.options.headers.range.replace('bytes=', '').split('-')[1]);
assert.strictEqual(reqEnd, end);
done();
});
});
});
describe('chunked with end range', () => {
it('Range added to download headers', done => {
const end = 1000;
const stream = ytdl.downloadFromInfo(expectedInfo, {
filter: 'audioonly',
range: { end },
});
stream.on('info', (info, format) => {
nock.url(format.url)
.reply(206);
});
stream.resume();
stream.on('error', done);
stream.on('request', req => {
const reqEnd = parseInt(req.options.headers.range.replace('bytes=', '').split('-')[1]);
assert.strictEqual(reqEnd, end);
done();
});
});
});
describe('with begin', () => {
it('Begin added to download URL', done => {
const stream = ytdl.downloadFromInfo(expectedInfo, { begin: '1m' });
stream.on('info', (info, format) => {
nock.url(`${format.url}&begin=60000`).reply(200, '');
});
stream.resume();
stream.on('error', done);
stream.on('end', done);
});
});
describe('With IPv6 Block', () => {
it('Sends request with IPv6 address', done => {
const stream = ytdl.downloadFromInfo(expectedInfo, { IPv6Block: '2001:2::/48' });
stream.on('info', (info, format) => {
nock.url(format.url)
.reply(206);
});
stream.on('request', req => {
assert.ok(net.isIPv6(req.options.localAddress));
done();
});
});
});
describe('Without IPv6 Block', () => {
it('Sends request with (default) IPv4 address', done => {
const stream = ytdl.downloadFromInfo(expectedInfo);
stream.on('info', (info, format) => {
nock.url(format.url)
.reply(206);
});
stream.on('request', req => {
assert.ok(req.options.localAddress === undefined);
done();
});
});
});
describe('with a bad filter', () => {
it('Emits error', done => {
const stream = ytdl.downloadFromInfo(expectedInfo, { filter: () => false });
stream.on('error', err => {
assert.ok(err);
assert.ok(/No such format found/.test(err.message));
done();
});
});
});
describe('that is broadcasted live', () => {
it('Begins downloading video succesfully', done => {
const testId = '5qap5aO4i9A';
const scope = nock(testId, 'live-now');
const stream = ytdl(testId, { filter: format => format.isHLS });
stream.on('info', (info, format) => {
scope.urlReply(format.url, 200, [
'#EXTM3U',
'#EXT-X-VERSION:3',
'#EXT-X-TARGETDURATION:8',
'#EXT-X-MEDIA-SEQUENCE:01',
'',
'#EXTINF:7.975,',
'/file01.ts',
'#EXTINF:7.941,',
'/file02.ts',
'#EXTINF:7.975,',
'/file03.ts',
'#EXT-X-ENDLIST',
].join('\n'));
const host = new URL(format.url).host;
scope.urlReply(`https://${host}/file01.ts`, 200, 'one', {
'content-length': '3',
});
scope.urlReply(`https://${host}/file02.ts`, 200, 'two', {
'content-length': '3',
});
scope.urlReply(`https://${host}/file03.ts`, 200, 'tres', {
'content-length': '4',
});
});
let body = '';
stream.setEncoding('utf8');
stream.on('data', chunk => { body += chunk; });
let progress = sinon.spy();
stream.on('progress', progress);
stream.on('end', () => {
assert.strictEqual(body, 'onetwotres');
assert.ok(progress.called);
assert.deepEqual(progress.args, [
[3, 1, 3],
[3, 2, 3],
[4, 3, 3],
]);
done();
});
});
describe('end download early', () => {
it('Stops downloading video', done => {
const testId = '5qap5aO4i9A';
const scope = nock(testId, 'live-now');
const stream = ytdl(testId);
stream.on('info', () => {
process.nextTick(() => {
stream.destroy();
scope.done();
done();
});
});
stream.on('data', () => { done(Error('should not emit `data`')); });
});
});
describe('from a dash-mpd itag', () => {
it('Begins downloading video succesfully', done => {
const testId = '5qap5aO4i9A';
let dashResponse = fs.readFileSync(path.resolve(__dirname, `files/videos/live-now/dash-manifest.xml`), 'utf8');
const replaceBetweenTags = (tagName, content) => {
const regex = new RegExp(`<${tagName}>(.+?)</${tagName}`, 'g');
dashResponse = dashResponse.replace(regex, `<${tagName}>${content}</${tagName}`);
};
// Create a playlist file that has only 3 short segments
// so we can easily mock these in tests.
replaceBetweenTags('SegmentTimeline', `
<S d="5000" /><S d="5000" /><S d="5000">
`);
replaceBetweenTags('BaseURL', 'https://googlevideo.com/videoplayback/');
replaceBetweenTags('SegmentList', `
<SegmentURL media="sq/video01.ts" />
<SegmentURL media="sq/video02.ts" />
<SegmentURL media="sq/video03.ts" />
`);
dashResponse = dashResponse.replace('type="dynamic"', '');
const scope = nock(testId, 'live-now', {
watchJson: false,
dashmpd: [true, 200, dashResponse],
});
const stream = ytdl(testId, { filter: format => format.isDashMPD });
stream.on('info', (info, format) => {
scope.urlReply(format.url, 200, dashResponse);
scope.urlReply(`https://googlevideo.com/videoplayback/sq/video01.ts`, 200, 'one');
scope.urlReply(`https://googlevideo.com/videoplayback/sq/video02.ts`, 200, 'two');
scope.urlReply(`https://googlevideo.com/videoplayback/sq/video03.ts`, 200, 'tres');
});
let body = '';
stream.setEncoding('utf8');
stream.on('data', chunk => { body += chunk; });
stream.on('end', () => {
scope.done();
assert.strictEqual(body, 'onetwotres');
done();
});
});
});
});
describe('that has not yet started broadcasting', () => {
it('Stream emits an error', done => {
const id = 'VIBFo3Ti5vQ';
const scope = nock(id, 'live-future');
let stream = ytdl(id, { requestOptions: { maxRetries: 0 } });
stream.on('error', err => {
scope.done();
assert.ok(/This live event will begin in/.test(err.message), `Error did not match: ${err.message}`);
done();
});
});
});
describe('From a rental', () => {
it('Stream emits an error', done => {
const id = 'SyKPsFRP_Oc';
const scope = nock(id, 'rental');
let stream = ytdl(id);
stream.on('error', err => {
scope.done();
assert.strictEqual(err.message, 'This video requires payment to watch.');
done();
});
stream.on('data', () => {
done(Error('should not emit `data`'));
});
stream.on('end', () => {
done(Error('should not emit `end`'));
});
});
});
describe('With no formats', () => {
it('Stream emits an error', done => {
const id = '_HSylqgVYQI';
const scope = nock(id, 'regular', {
watchHtml: [true, 200, body => body.replace(/\b(formats|adaptiveFormats)\b/g, 'no')],
watchJson: false,
get_video_info: false,
player: false,
});
let stream = ytdl(id);
stream.on('error', err => {
scope.done();
assert.strictEqual(err.message, 'This video is unavailable');
done();
});
stream.on('data', () => {
done(Error('should not emit `data`'));
});
stream.on('end', () => {
done(Error('should not emit `end`'));
});
});
});
});