This repository has been archived by the owner on Sep 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 58
/
cli.js
executable file
·106 lines (91 loc) · 2.19 KB
/
cli.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
#!/usr/bin/env node
'use strict'
const meow = require('meow')
const logSymbols = require('log-symbols')
const shell = require('shelljs')
const ora = require('ora')
const updateNotifier = require('update-notifier')
const chalk = require('chalk')
const ytdlApi = require('./ytdl-api')
const menu = require('./menu')
const pkg = require('./package.json')
const cli = meow(
`
Usage: youtube-dl-interactive URL
Options:
--help, -h output usage information
--version output the version number
--demo use sample data, no remote calls
`,
{
flags: {
demo: {
type: 'boolean'
}
}
}
)
async function init(args, flags) {
if (!shell.which('youtube-dl')) {
shell.echo('Sorry, this script requires youtube-dl.')
shell.echo('See https://github.com/ytdl-org/youtube-dl.')
shell.exit(1)
}
updateNotifier({pkg}).notify()
if (flags.demo) {
console.log(
logSymbols.warning,
chalk.bgYellowBright(
'Running demo with sample data, not actually calling youtube-dl.'
)
)
await run(null, true)
} else {
if (args.length !== 1) {
cli.showHelp(1)
}
const url = args[0]
await run(url, false)
}
}
init(cli.input, cli.flags).catch(error => {
console.error(error)
process.exit(1)
})
async function run(url, isDemo) {
const info = isDemo
? require('./test/samples/thankyousong.json')
: await fetchInfo(url)
if (!info) {
return
}
console.log(chalk.bold('Title:', chalk.blue(info.title)))
const {formats} = info
const {formatString, hasVideo, hasAudio} = await menu.formatMenu(formats)
let options = ` -f '${formatString}' --restrict-filenames `
if (!hasVideo && hasAudio) {
options += ' --extract-audio '
}
if (isDemo) {
console.log(
logSymbols.warning,
`End of demo. would now call: youtube-dl ${options} <url>"`
)
} else {
const command = `youtube-dl ${options} "${url}"`
console.log(logSymbols.success, `OK. Running: ${command}`)
shell.exec(command)
}
}
async function fetchInfo(url) {
const spinner = ora('Loading metadata').start()
try {
const info = await ytdlApi.getInfo(url)
spinner.stop()
return info
} catch (error) {
spinner.fail('Error while loading metadata')
console.error(error)
return null
}
}