forked from rylio/ytdl
/
utils.go
94 lines (85 loc) · 2.35 KB
/
utils.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
package main
import (
"bytes"
"fmt"
"regexp"
"strings"
"text/template"
"github.com/rylio/ytdl"
)
func parseFilter(filterString string) (func(ytdl.FormatList) ytdl.FormatList, error) {
filterString = strings.TrimSpace(filterString)
switch filterString {
case "best", "worst":
return func(formats ytdl.FormatList) ytdl.FormatList {
return formats.Extremes(ytdl.FormatResolutionKey, filterString == "best").Extremes(ytdl.FormatAudioBitrateKey, filterString == "best")
}, nil
case "best-video", "worst-video":
return func(formats ytdl.FormatList) ytdl.FormatList {
return formats.Extremes(ytdl.FormatResolutionKey, strings.HasPrefix(filterString, "best"))
}, nil
case "best-audio", "worst-audio":
return func(formats ytdl.FormatList) ytdl.FormatList {
return formats.Extremes(ytdl.FormatAudioBitrateKey, strings.HasPrefix(filterString, "best"))
}, nil
}
err := fmt.Errorf("Invalid filter")
split := strings.SplitN(filterString, ":", 2)
if len(split) != 2 {
return nil, err
}
key := ytdl.FormatKey(split[0])
exclude := key[0] == '!'
if exclude {
key = key[1:]
}
value := strings.TrimSpace(split[1])
if value == "best" || value == "worst" {
return func(formats ytdl.FormatList) ytdl.FormatList {
f := formats.Extremes(key, value == "best")
if exclude {
f = formats.Subtract(f)
}
return f
}, nil
}
vals := strings.Split(value, ",")
values := make([]interface{}, len(vals))
for i, v := range vals {
values[i] = strings.TrimSpace(v)
}
return func(formats ytdl.FormatList) ytdl.FormatList {
f := formats.Filter(key, values)
if exclude {
f = formats.Subtract(f)
}
return f
}, nil
}
type outputFileName struct {
Title string
Author string
Ext string
DatePublished string
Resolution string
Duration string
}
var fileNameTemplate = template.New("OutputFileName")
func createFileName(template string, values outputFileName) (string, error) {
t, err := fileNameTemplate.Parse(template)
if err != nil {
return "", err
}
buf := &bytes.Buffer{}
err = t.Execute(buf, values)
if err != nil {
return "", err
}
return string(buf.String()), nil
}
var illegalFileNameCharacters = regexp.MustCompile(`[^[a-zA-Z0-9]-_]`)
func sanitizeFileNamePart(part string) string {
part = strings.Replace(part, "/", "-", -1)
part = illegalFileNameCharacters.ReplaceAllString(part, "")
return part
}