Repository navigation
Expand file tree
/
Copy pathmain.ts
More file actions
763 lines (663 loc) · 23.1 KB
/
Copy pathmain.ts
File metadata and controls
763 lines (663 loc) · 23.1 KB
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
756
757
758
759
760
761
762
763
import type {
DownloadCount,
DownloadYouTubePlaylistInput,
DownloadYouTubePlaylistOutput,
Failure,
PartialVideo,
PartialVideoWithDuration,
Video,
} from './types'
import type {youtube_v3} from '@googleapis/youtube'
import type {GaxiosResponse} from 'googleapis-common'
import fs from 'node:fs'
import google from '@googleapis/youtube'
import {chunkArray, createLogger, emptyLog, pluralize} from '@qodestack/utils'
import {$} from 'bun'
import cliProgress from 'cli-progress'
import {safeParse} from 'valibot'
import {
PlaylistItemSchema,
VideosListItemSchema,
YtDlpJsonSchema,
} from './schemas'
import {
downloadThumbnailFile,
genPlaylistItems,
getLufsForFile,
MAX_YOUTUBE_RESULTS,
mkdirSafe,
parseISO8601DurationToSeconds,
sanitizeTime,
} from './utils'
export {downloadYouTubeVideo} from './downloadYouTubeVideo'
export async function downloadYouTubePlaylist(
options: DownloadYouTubePlaylistInput
): Promise<DownloadYouTubePlaylistOutput> {
const {
// Required options.
playlistId,
youTubeApiKey,
downloadType,
// Optional options.
maxDurationSeconds = Infinity,
mostRecentItemsCount,
silent = false,
timeZone,
maxConcurrentYouTubeCalls = 4,
maxConcurrentYtdlpCalls = 10,
} = options
const log = createLogger({timeZone})
const logger = silent ? emptyLog : log
const processStart = performance.now()
/**
* Instead of exiting the process when something fails, we store metadata
* about the failures and continue the process. Failures are then returned
* to the user for further action.
*/
const failures: Failure[] = []
/**
* *********
* STEP 1: *
* *********
* Check for system dependencies.
*
* yt-dlp is the package we use to download videos from a YouTube playlist.
* ffmpeg is the package that yt-dlp uses under the hood to convert videos to
* audio files. Check for both of these before proceeding and provide a
* helpful message if any are missing. The process will exit with an error
* without returning anything if dependencies are missing.
*/
logger.text('Checking for yt-dlp and ffmpeg...')
const ytDlpPath = Bun.which('yt-dlp')
const ffmpegPath = Bun.which('ffmpeg')
if (ytDlpPath === null) {
logger.error('\nCould not find the `yt-dlp` package on this system.')
logger.error('This package is needed to download YouTube videos.')
logger.error(
'Please head to https://github.com/yt-dlp/yt-dlp for download instructions.'
)
}
if (ffmpegPath === null) {
logger.error('\nCould not find the `ffmpeg` package on this system.')
logger.error('This package is needed to extract audio from YouTube videos.')
logger.error(
'You can download a binary at https://www.ffmpeg.org/download.html or run `brew install ffmpeg`.'
)
}
if (!ytDlpPath || !ffmpegPath) {
throw new Error('Missing `yt-dlp` or `ffmpeg`')
}
logger.text('`yt-dlp` and `ffmpeg` are present!')
/**
* *********
* STEP 2: *
* *********
* Get metadata for each video.
*
* See comments on the `Video` type for where each field comes from in the
* YouTube API. Depending on the input variables we will either fetch the
* entire playlist or the most recent specified number of videos. This is
* helpful when running in a cron job where we don't need to fetch the entire
* playlist each time.
*/
// The YouTube API client.
const yt = google.youtube({version: 'v3', auth: youTubeApiKey})
const startYouTubeCalls = performance.now()
logger.text(
`Getting partial video metadata for ${
mostRecentItemsCount !== undefined
? pluralize(mostRecentItemsCount, 'item')
: 'all items'
}...`
)
/**
* This object stores how many times the YouTube APIs are called throughout
* the entire process. This is helpful to gauge against quotas.
*/
const youTubeFetchCount = {count: 0}
/**
* Raw responses from the YouTube
* [PlaylistItems API](https://developers.google.com/youtube/v3/docs/playlistItems)
* getting playlist-level metadata for each video (this includes most of the
* metadata we'll need).
*/
const playlistItemListResponses = await genPlaylistItems({
yt,
playlistId,
youTubeFetchCount,
// Default to Infinity, representing all items.
totalItemsToFetch: mostRecentItemsCount || Infinity,
}).catch(error => {
failures.push({
type: 'generic',
error,
date: Date.now(),
context: 'genPlaylistItems',
})
return []
})
/**
* A flattened and massaged list of metadata for videos based on the initial
* [PlaylistItems API](https://developers.google.com/youtube/v3/docs/playlistItems)
* call. This metadata lacks file extensions and certain properties only
* returned from the
* [VideosList API](https://developers.google.com/youtube/v3/docs/videos/list)
* API call later on.
*/
const partialVideosMetadata: PartialVideo[] =
playlistItemListResponses.reduce<PartialVideo[]>((acc, response) => {
response.data.items?.forEach(item => {
const results = safeParse(PlaylistItemSchema, item)
if (!results.success) {
failures.push({
type: 'schemaParse',
schemaName: 'PlaylistItemSchema',
issues: results.issues,
date: Date.now(),
})
} else {
const {snippet, contentDetails} = results.output
const isUnavailable =
snippet.title === 'Private video' ||
snippet.title === 'Deleted video'
acc.push({
id: snippet.resourceId.videoId,
playlistItemId: results.output.id,
title: snippet.title,
description: snippet.description,
channelId: snippet.videoOwnerChannelId,
channelName: snippet.videoOwnerChannelTitle,
dateCreated: contentDetails.videoPublishedAt,
dateAddedToPlaylist: snippet.publishedAt,
/**
* Sometimes YouTube returns a 404 response for these urls. We store
* multiple urls in highest quality descending order so that when we
* go to download a thumbnail we get the best available version.
*/
thumbnailUrls: [
snippet.thumbnails.maxres?.url,
snippet.thumbnails.standard?.url,
snippet.thumbnails.high?.url,
snippet.thumbnails.medium?.url,
snippet.thumbnails.default?.url,
].filter(Boolean) as string[],
url: `https://www.youtube.com/watch?v=${snippet.resourceId.videoId}`,
channelUrl: `https://www.youtube.com/channel/${snippet.videoOwnerChannelId}`,
isUnavailable,
})
}
})
return acc
}, [])
/**
* An object version of a flattened and massaged list of metadata for videos,
* based on the initial
* [PlaylistItems API](https://developers.google.com/youtube/v3/docs/playlistItems)
* call, so we can directly access a partial video object by its id. This
* metadata lacks file extensions and certain properties only returned by the
* [VideosList API](https://developers.google.com/youtube/v3/docs/videos/list)
* API call later on.
*/
const partialVideosMetadataObj = partialVideosMetadata.reduce<
Record<string, PartialVideo>
>((acc, partialVideo) => {
acc[partialVideo.id] = partialVideo
return acc
}, {})
/**
* Now that we've retrieved everything the
* [PlaylistItems API](https://developers.google.com/youtube/v3/docs/playlistItems)
* will give us, separate the unavailable videos from available videos. For
* unavailable videos, we add the missing metadata to make them adhere to the
* `Video` type. For available videos, we need their ids which will be used
* by the
* [VideosList API](https://developers.google.com/youtube/v3/docs/videos/list)
* coming up to fetch the rest of their metadata.
*/
const partialVideoReductionData = partialVideosMetadata.reduce<{
videoIdsToFetch: string[]
unavailableVideos: Video[]
}>(
(acc, partialVideo) => {
if (partialVideo.isUnavailable) {
acc.unavailableVideos.push({
...partialVideo,
durationInSeconds: 0,
audioFileExtension: null,
videoFileExtension: null,
lufs: null,
})
} else {
acc.videoIdsToFetch.push(partialVideo.id)
}
return acc
},
{videoIdsToFetch: [], unavailableVideos: []}
)
// Creating separate variables with comments for intellisense when hovering.
/**
* Unavailable videos from the recent call to the
* [PlaylistItems API](https://developers.google.com/youtube/v3/docs/playlistItems).
*/
const unavailableVideos = partialVideoReductionData.unavailableVideos
/**
* Ids for all the available videos from the
* [PlaylistItems API](https://developers.google.com/youtube/v3/docs/playlistItems)
* call.
*/
const videoIdsToFetch = partialVideoReductionData.videoIdsToFetch
logger.text(
`Getting remaining video metadata for ${pluralize(
videoIdsToFetch.length,
'item'
)}...`
)
/**
* Since the YouTube APIs can retrieve up to 50 items in a single fetch call,
* create an array of id arrays that are 50 ids each:
*
* ```
* [[50 ids], [50 ids], ...]
* ```
*/
const chunkedVideoIdsToFetch = chunkArray(
videoIdsToFetch,
MAX_YOUTUBE_RESULTS
)
/**
* A single call to the
* [VideosList API](https://developers.google.com/youtube/v3/docs/videos/list)
* can specify a max of 50 ids. We want to run a number of concurrent fetch
* calls, so further chunk the array.
*
* For example, 4 max concurrent calls would create this 3D array:
*
* ```
* [
* [[50 ids], [50 ids], [50 ids], [50 ids]],
* [[50 ids], [50 ids], [50 ids], [50 ids]],
* ...
* ]
* ```
*/
const fetchIdChunks = chunkArray(
chunkedVideoIdsToFetch,
maxConcurrentYouTubeCalls
)
/**
* Raw responses from the YouTube
* [VideosList API](https://developers.google.com/youtube/v3/docs/videos/list).
* This gets the remaining metadata for each video.
*/
const videoListResponses = await fetchIdChunks
.reduce<
Promise<(GaxiosResponse<youtube_v3.Schema$VideoListResponse> | null)[]>
>((promise, idArrays) => {
return promise.then(previousResults =>
Promise.allSettled(
// `idArrays` represents how many concurrent promises we want to run.
idArrays.map(ids => {
youTubeFetchCount.count++
return yt.videos.list({id: ids, part: ['contentDetails']})
})
).then(results => {
const successfullResults: (GaxiosResponse<youtube_v3.Schema$VideoListResponse> | null)[] =
[]
results.forEach((response, resultIndex) => {
if (response.status === 'fulfilled') {
successfullResults.push(response.value)
} else {
failures.push({
type: 'videosListApi',
error: response.reason,
ids: idArrays[resultIndex],
date: Date.now(),
})
/**
* We store a null value to maintain the correct array index for the
* API call.
*/
successfullResults.push(null)
}
})
return previousResults.concat(successfullResults)
})
)
}, Promise.resolve([]))
.catch(error => {
failures.push({
type: 'generic',
error,
date: Date.now(),
context: 'fetchIdChunks.reduce',
})
return []
})
/**
* Construct an object of formatted durations for each video from the
* [VideosList API](https://developers.google.com/youtube/v3/docs/videos/list)
* call. This will be used to add duration data to the final metadata.
*/
const durationsObj = videoListResponses.reduce<Record<string, number>>(
(acc, response) => {
response?.data.items?.forEach(item => {
const parsedResults = safeParse(VideosListItemSchema, item)
if (!parsedResults.success) {
failures.push({
type: 'schemaParse',
schemaName: 'VideosListItemSchema',
issues: parsedResults.issues,
date: Date.now(),
})
return
}
const {id, contentDetails} = parsedResults.output
const duration = contentDetails.duration
const partialVideo = partialVideosMetadataObj[id]
if (!partialVideo) {
failures.push({type: 'partialVideoNotFound', id, date: Date.now()})
} else {
acc[id] = parseISO8601DurationToSeconds(duration)
}
})
return acc
},
{}
)
// Add duration times to the partial metadata we have so far.
const partialVideosWithDurationMetadata: PartialVideoWithDuration[] =
partialVideosMetadata.map(partialVideo => {
const durationInSeconds = durationsObj[partialVideo.id] ?? 0
return {...partialVideo, durationInSeconds}
})
// An obj with all the video metadata we have so far for reference later.
const partialVideosWthDurationObj = partialVideosWithDurationMetadata.reduce<
Record<string, PartialVideo & {durationInSeconds: number}>
>((acc, {durationInSeconds, ...partialVideo}) => {
acc[partialVideo.id] = {...partialVideo, durationInSeconds}
return acc
}, {})
const fetchMetadataTime = sanitizeTime(performance.now() - startYouTubeCalls)
logger.text(`Video metadata received! [${fetchMetadataTime}]`)
/**
* *********
* STEP 3: *
* *********
* Determine which videos need to be downloaded.
*
* We compare our metadata to what we have in the system. We want to avoid
* using the files in `directory` as the source of truth since a database
* might be involved on the user's end. We keep the source of truth agnostic
* by having the user provide a `getIdsForDownload` function that filters out
* which ids to download, leaving that logic up to the user. Ids returned from
* that function represent videos to download.
*/
const idsToDownload = await (async () => {
if (downloadType === 'none') return []
/**
* Filter the metadata from the YouTube APIs to determine which videos we
* will potentially download:
* - The video isn't longer than `maxDurationSeconds`
* - The video is available according to the YouTube APIs
*/
const potentialIds = partialVideosWithDurationMetadata.reduce<string[]>(
(acc, {id, durationInSeconds, isUnavailable}) => {
if (durationInSeconds <= maxDurationSeconds && !isUnavailable) {
acc.push(id)
}
return acc
},
[]
)
/**
* Determine which videos we will actually download. Logic is left up to the
* consumer. For example, a consumer may check if the file is on disk or if
* a database already has an entry for a given id. `getIdsForDownload` will
* determine which ids out of the batch should be downloaded.
*/
return await Promise.resolve(options.getIdsForDownload(potentialIds)).catch(
error => {
failures.push({
type: 'generic',
error,
date: Date.now(),
context: 'getIdsForDownload',
})
return []
}
)
})()
/**
* *********
* STEP 4: *
* *********
* Download the videos.
*
* We will create the directories needed conditionally.
*/
const downloadCount: DownloadCount = {audio: 0, video: 0, thumbnail: 0}
if (downloadType === 'none') {
logger.success(
`Process complete! [${sanitizeTime(performance.now() - processStart)}]`
)
return {
playlistItemListResponses,
videoListResponses,
videosDownloaded: [],
unavailableVideos,
failures,
downloadCount,
youTubeFetchCount: youTubeFetchCount.count,
}
}
const {directory, downloadThumbnails} = options
const audioDir = `${directory}/audio`
const videoDir = `${directory}/video`
const thumbnailDirectory = `${directory}/thumbnails`
// Create directories only if there are videos to download.
if (idsToDownload.length) {
// Create audio directory.
if (downloadType === 'audio' || downloadType === 'both') {
mkdirSafe(audioDir)
}
// Create video directory.
if (downloadType === 'video' || downloadType === 'both') {
mkdirSafe(videoDir)
}
// Create thumnails directory.
if (downloadThumbnails) {
mkdirSafe(thumbnailDirectory)
}
}
const startProcessing = performance.now()
const downloadProgressBar = new cliProgress.SingleBar(
{
format: '👉 {bar} {percentage}% | {value}/{total} | {duration_formatted}',
// barsize: Math.round(process.stdout.columns * 0.75),
stopOnComplete: true,
},
cliProgress.Presets.shades_grey
)
const audioTemplate = `${directory}/audio/%(id)s.%(ext)s`
const videoTemplate = `${directory}/video/%(id)s.%(ext)s`
const downloadPromiseFxns: (() => Promise<Video | null>)[] = (
idsToDownload ?? []
).map(id => {
return async () => {
const partialVideo = partialVideosWthDurationObj[id]
if (!partialVideo) {
failures.push({type: 'partialVideoNotFound', id, date: Date.now()})
return null
}
if (downloadThumbnails) {
await downloadThumbnailFile({
urls: partialVideo.thumbnailUrls,
id,
thumbnailDirectory,
})
.then(() => {
downloadCount.thumbnail++
})
.catch((failure: Failure) => {
failures.push(failure)
})
}
const {url} = partialVideo
const {shellPromise, template} = (() => {
if (downloadType === 'audio') {
const {audioFormat} = options
return {
shellPromise: $`yt-dlp -o "${audioTemplate}" --extract-audio --audio-format="${audioFormat}" -J --no-simulate ${url}`,
template: `yt-dlp -o "${audioTemplate}" --extract-audio --audio-format="${audioFormat}" -J --no-simulate ${url}`,
}
}
if (downloadType === 'video') {
const {videoFormat} = options
return {
shellPromise: $`yt-dlp -o "${videoTemplate}" --format="${videoFormat}" -J --no-simulate ${url}`,
template: `yt-dlp -o "${videoTemplate}" --format="${videoFormat}" -J --no-simulate ${url}`,
}
}
const {audioFormat, videoFormat} = options
return {
shellPromise: $`yt-dlp -o "${videoTemplate}" --format="${videoFormat}" --extract-audio --audio-format="${audioFormat}" -k -J --no-simulate ${url}`,
template: `yt-dlp -o "${videoTemplate}" --format="${videoFormat}" --extract-audio --audio-format="${audioFormat}" -k -J --no-simulate ${url}`,
}
})()
return shellPromise
.nothrow() // Necessary to ensure `.then` is populated with `exitCode`.
.quiet() // Avoid printing to stdout.
.then(({exitCode, stdout, stderr}) => {
downloadProgressBar.increment()
if (exitCode !== 0) {
failures.push({
type: 'ytdlpFailure',
url,
template,
stderr: stderr.toString(),
date: Date.now(),
})
return null
}
if (downloadType === 'audio' || downloadType === 'both') {
downloadCount.audio++
}
if (downloadType === 'video' || downloadType === 'both') {
downloadCount.video++
}
const parsedResults = safeParse(
YtDlpJsonSchema,
JSON.parse(stdout.toString())
)
if (!parsedResults.success) {
failures.push({
type: 'schemaParse',
schemaName: 'YtDlpJsonSchema',
issues: parsedResults.issues,
date: Date.now(),
})
return null
}
const {ext, requested_downloads} = parsedResults.output
const audioFileExtension = requested_downloads[0]?.ext
const audioFilePath = `${audioDir}/${id}.${audioFileExtension}`
const videoFilePath = `${videoDir}/${id}.${ext}`
if (downloadType === 'both') {
/**
* The ytdlp template will download the video and audio files into the
* video directory. We manually move the audio file here.
*/
const currentAudioPath = `${videoDir}/${id}.${audioFileExtension}`
fs.renameSync(currentAudioPath, audioFilePath)
}
const lufsFilePath =
downloadType === 'video' ? videoFilePath : audioFilePath
const lufs = getLufsForFile(lufsFilePath)
const isLufsValid = typeof lufs === 'number'
if (!isLufsValid) {
failures.push({
type: 'lufs',
filePath: lufsFilePath,
errorMessage: lufs.error,
date: Date.now(),
})
}
return {
...partialVideo,
audioFileExtension: audioFileExtension ?? null,
videoFileExtension: downloadType === 'audio' ? null : ext,
lufs: isLufsValid ? lufs : null,
}
})
.catch(error => {
failures.push({
type: 'generic',
error,
date: Date.now(),
context: `downloadPromiseFxns => shellPromise => id - ${id}`,
})
return null
})
}
})
if (!downloadPromiseFxns.length) {
logger.text('All videos accounted for, nothing to download!')
logger.success(
`Process complete! [${sanitizeTime(performance.now() - processStart)}]`
)
return {
playlistItemListResponses,
videoListResponses,
videosDownloaded: [],
unavailableVideos,
failures,
downloadCount,
youTubeFetchCount: youTubeFetchCount.count,
}
}
logger.text(
`Downloading ${pluralize(downloadPromiseFxns.length, 'playlist item')}...`
)
if (!silent) {
downloadProgressBar.start(downloadPromiseFxns.length, 0)
}
const promiseFxnBatches = chunkArray(
downloadPromiseFxns,
maxConcurrentYtdlpCalls
)
// The actual download!
const videosDownloaded = await promiseFxnBatches.reduce<Promise<Video[]>>(
(promise, promiseFxnBatch) => {
return promise.then(previousResults => {
return Promise.allSettled(promiseFxnBatch.map(f => f())).then(
newResults => {
const successfulResults: Video[] = []
newResults.forEach(response => {
// Errors already handled in the promise functions above.
if (response.status === 'fulfilled' && response.value !== null) {
successfulResults.push(response.value)
}
})
return previousResults.concat(successfulResults)
}
)
})
},
Promise.resolve([])
)
downloadProgressBar.stop()
const processingTime = sanitizeTime(performance.now() - startProcessing)
logger.text(`Downloading complete! [${processingTime}]`)
logger.success(
`Process complete! [${sanitizeTime(performance.now() - processStart)}]`
)
return {
playlistItemListResponses,
videoListResponses,
videosDownloaded,
unavailableVideos,
failures,
downloadCount,
youTubeFetchCount: youTubeFetchCount.count,
}
}