forked from rylio/ytdl
/
main.go
290 lines (276 loc) · 7.46 KB
/
main.go
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
package main
import (
"fmt"
"io"
"net/http"
"os"
"runtime"
"strconv"
"time"
"encoding/json"
log "github.com/Sirupsen/logrus"
"github.com/cheggaaa/pb"
"github.com/codegangsta/cli"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
"github.com/rylio/ytdl"
)
type options struct {
noProgress bool
outputFile string
infoOnly bool
silent bool
debug bool
append bool
filters []string
downloadURL bool
byteRange string
json bool
startOffset string
}
func main() {
app := cli.NewApp()
app.Name = "ytdl"
app.HelpName = "ytdl"
// Set our own custom args usage
app.ArgsUsage = "[youtube url or video id]"
app.Usage = "Download youtube videos"
app.HideHelp = true
app.Version = "0.5.0"
app.Flags = []cli.Flag{
cli.HelpFlag,
cli.StringFlag{
Name: "output, o",
Usage: "Write output to a file, passing - outputs to stdout",
Value: "{{.Title}}.{{.Ext}}",
},
cli.BoolFlag{
Name: "info, i",
Usage: "Only output video info",
},
cli.BoolFlag{
Name: "no-progress",
Usage: "Disable the progress bar",
},
cli.BoolFlag{
Name: "silent, s",
Usage: "Only output errors, also disables progress bar",
},
cli.BoolFlag{
Name: "debug, d",
Usage: "Output debug log",
},
cli.BoolFlag{
Name: "append, a",
Usage: "Append to output file instead of overwriting",
},
cli.StringSliceFlag{
Name: "filter, f",
Usage: "Filter available formats, syntax: [format_key]:val1,val2",
},
cli.StringFlag{
Name: "range, r",
Usage: "Download a specific range of bytes of the video, [start]-[end]",
},
cli.BoolFlag{
Name: "download-url, u",
Usage: "Prints download url to stdout",
},
cli.BoolFlag{
Name: "json, j",
Usage: "Print info json to stdout",
},
cli.StringFlag{
Name: "start-offset",
Usage: "Offset the start of the video by time",
},
}
app.Action = func(c *cli.Context) error {
identifier := c.Args().First()
if identifier == "" || c.Bool("help") {
cli.ShowAppHelp(c)
} else {
options := options{
noProgress: c.Bool("no-progress"),
outputFile: c.String("output"),
infoOnly: c.Bool("info"),
silent: c.Bool("silent"),
debug: c.Bool("debug"),
append: c.Bool("append"),
filters: c.StringSlice("filter"),
downloadURL: c.Bool("download-url"),
byteRange: c.String("range"),
json: c.Bool("json"),
startOffset: c.String("start-offset"),
}
if len(options.filters) == 0 {
options.filters = cli.StringSlice{
fmt.Sprintf("%s:mp4", ytdl.FormatExtensionKey),
fmt.Sprintf("!%s:", ytdl.FormatVideoEncodingKey),
fmt.Sprintf("!%s:", ytdl.FormatAudioEncodingKey),
fmt.Sprint("best"),
}
}
handler(identifier, options)
}
return nil
}
app.Run(os.Args)
}
func handler(identifier string, options options) {
var err error
defer func() {
if err != nil {
log.SetOutput(os.Stderr)
log.Fatal(err.Error())
}
}()
var out io.Writer
var logOut io.Writer = os.Stdout
if runtime.GOOS == "windows" && isatty.IsTerminal(os.Stdout.Fd()) {
logOut = colorable.NewColorableStdout()
log.SetFormatter(&log.TextFormatter{ForceColors: true})
}
// if downloading to stdout, set log output to stderr, not sure if this is correct
if options.outputFile == "-" {
out = os.Stdout
logOut = os.Stderr
}
log.SetOutput(logOut)
// ouput only errors or not
silent := options.outputFile == "" ||
options.silent || options.infoOnly || options.downloadURL || options.json
if silent {
log.SetLevel(log.FatalLevel)
} else if options.debug {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(log.InfoLevel)
}
// TODO: Show activity indicator
log.Info("Fetching video info...")
//fmt.Print("\u001b[0G")
//fmt.Print("\u001b[2K")
info, err := ytdl.GetVideoInfo(identifier)
if err != nil {
err = fmt.Errorf("Unable to fetch video info: %s", err.Error())
return
}
if options.infoOnly {
fmt.Println("Title:", info.Title)
fmt.Println("Author:", info.Author)
fmt.Println("Date Published:", info.DatePublished.Format("Jan 2 2006"))
fmt.Println("Duration:", info.Duration)
return
} else if options.json {
var data []byte
data, err = json.MarshalIndent(info, "", "\t")
if err != nil {
err = fmt.Errorf("Unable to marshal json: %s", err.Error())
return
}
fmt.Println(string(data))
return
}
formats := info.Formats
// parse filter arguments, and filter through formats
for _, filter := range options.filters {
filter, err := parseFilter(filter)
if err == nil {
formats = filter(formats)
}
}
if len(formats) == 0 {
err = fmt.Errorf("No formats available that match criteria")
return
}
format := formats[0]
downloadURL, err := info.GetDownloadURL(format)
if err != nil {
err = fmt.Errorf("Unable to get download url: %s", err.Error())
return
}
if options.startOffset != "" {
var offset time.Duration
offset, err = time.ParseDuration(options.startOffset)
query := downloadURL.Query()
query.Set("begin", fmt.Sprint(int64(offset/time.Millisecond)))
downloadURL.RawQuery = query.Encode()
}
if options.downloadURL {
fmt.Print(downloadURL.String())
// print new line character if outputing to terminal
if isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Println()
}
return
}
if out == nil {
var fileName string
fileName, err = createFileName(options.outputFile, outputFileName{
Title: sanitizeFileNamePart(info.Title),
Ext: sanitizeFileNamePart(format.Extension),
DatePublished: sanitizeFileNamePart(info.DatePublished.Format("2006-01-02")),
Resolution: sanitizeFileNamePart(format.Resolution),
Author: sanitizeFileNamePart(info.Author),
Duration: sanitizeFileNamePart(info.Duration.String()),
})
if err != nil {
err = fmt.Errorf("Unable to parse output file file name: %s", err.Error())
return
}
// Create file truncate if append flag is not set
flags := os.O_CREATE | os.O_WRONLY
if options.append {
flags |= os.O_APPEND
} else {
flags |= os.O_TRUNC
}
var f *os.File
// open as write only
f, err = os.OpenFile(fileName, flags, 0666)
if err != nil {
err = fmt.Errorf("Unable to open output file: %s", err.Error())
return
}
defer f.Close()
out = f
}
log.Info("Downloading to ", out.(*os.File).Name())
var req *http.Request
req, err = http.NewRequest("GET", downloadURL.String(), nil)
// if byte range flag is set, use http range header option
if options.byteRange != "" || options.append {
if options.byteRange == "" && out != os.Stdout {
if stat, err := out.(*os.File).Stat(); err != nil {
options.byteRange = strconv.FormatInt(stat.Size(), 10) + "-"
}
}
if options.byteRange != "" {
req.Header.Set("Range", "bytes="+options.byteRange)
}
}
resp, err := http.DefaultClient.Do(req)
if err != nil || resp.StatusCode < 200 || resp.StatusCode >= 300 {
if err == nil {
err = fmt.Errorf("Received status code %d from download url", resp.StatusCode)
}
err = fmt.Errorf("Unable to start download: %s", err.Error())
return
}
defer resp.Body.Close()
// if we aren't in silent mode or the no progress flag wasn't set,
// initialize progress bar
if !silent && !options.noProgress {
progressBar := pb.New64(resp.ContentLength)
progressBar.SetUnits(pb.U_BYTES)
progressBar.ShowTimeLeft = true
progressBar.ShowSpeed = true
// progressBar.RefreshRate = time.Millisecond * 1
progressBar.Output = logOut
progressBar.Start()
defer progressBar.Finish()
out = io.MultiWriter(out, progressBar)
}
_, err = io.Copy(out, resp.Body)
}