1
1
'use strict'
2
2
3
- const { writeFile, mkdir } = require ( 'fs/promises' )
4
- const { concat } = require ( 'simple-get' )
5
-
6
- const mkdirp = filepath => mkdir ( filepath , { recursive : true } ) . catch ( ( ) => { } )
7
-
8
- const get = url =>
9
- new Promise ( ( resolve , reject ) =>
10
- concat (
11
- {
12
- url,
13
- headers : {
14
- 'user-agent' : 'microlinkhq/youtube-dl-exec'
15
- }
16
- } ,
17
- ( err , response , data ) => ( err ? reject ( err ) : resolve ( { response, data } ) )
18
- )
19
- )
3
+ const debug = require ( 'debug-logfmt' ) ( 'youtube-dl-exec:install' )
4
+ const { mkdir, chmod } = require ( 'node:fs/promises' )
5
+ const { pipeline } = require ( 'node:stream/promises' )
6
+ const { createWriteStream } = require ( 'node:fs' )
20
7
21
8
const {
22
9
YOUTUBE_DL_PATH ,
@@ -26,23 +13,31 @@ const {
26
13
YOUTUBE_DL_SKIP_DOWNLOAD
27
14
} = require ( '../src/constants' )
28
15
29
- const getLatest = data => {
30
- const { assets } = JSON . parse ( data )
16
+ const getLatest = ( { assets } ) => {
31
17
const { browser_download_url : url } = assets . find (
32
18
( { name } ) => name === YOUTUBE_DL_FILE
33
19
)
34
- return get ( url ) . then ( ( { data } ) => data )
20
+ return fetch ( url )
35
21
}
36
22
37
23
const getBinary = async url => {
38
- const { response, data } = await get ( url )
39
- return response . headers [ 'content-type' ] === 'application/octet-stream'
40
- ? data
41
- : getLatest ( data )
24
+ let response = await fetch ( url )
25
+ if ( response . headers . get ( 'content-type' ) !== 'application/octet-stream' ) {
26
+ response = await getLatest ( await response . json ( ) )
27
+ }
28
+ return response . body
42
29
}
43
30
44
- if ( ! YOUTUBE_DL_SKIP_DOWNLOAD ) {
45
- Promise . all ( [ getBinary ( YOUTUBE_DL_HOST ) , mkdirp ( YOUTUBE_DL_DIR ) ] )
46
- . then ( ( [ buffer ] ) => writeFile ( YOUTUBE_DL_PATH , buffer , { mode : 0o755 } ) )
47
- . catch ( err => console . error ( err . message || err ) )
31
+ const installBinary = async ( ) => {
32
+ debug ( 'downloading' , { url : YOUTUBE_DL_HOST } )
33
+ const [ binary ] = await Promise . all ( [
34
+ getBinary ( YOUTUBE_DL_HOST ) ,
35
+ mkdir ( YOUTUBE_DL_DIR , { recursive : true } )
36
+ ] )
37
+ debug ( 'writing' , { path : YOUTUBE_DL_PATH } )
38
+ await pipeline ( binary , createWriteStream ( YOUTUBE_DL_PATH ) )
39
+ await chmod ( YOUTUBE_DL_PATH , 0o755 )
40
+ debug ( { status : 'success' } )
48
41
}
42
+
43
+ YOUTUBE_DL_SKIP_DOWNLOAD ? debug ( { status : 'skipped' } ) : installBinary ( )
0 commit comments