-
Notifications
You must be signed in to change notification settings - Fork 0
/
ytdl.go
117 lines (96 loc) · 2.57 KB
/
ytdl.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
package metadata
import (
"encoding/json"
"fmt"
"os"
"path"
"strings"
"github.com/ghetzel/go-stockutil/maputil"
"github.com/ghetzel/go-stockutil/stringutil"
)
var DefaultExcludeFields = []string{
`_filename`,
`description`,
`dislike_count`,
`formats`,
`http_headers`,
`like_count`,
`thumbnails`,
`url`,
`view_count`,
}
type YTDLLoader struct {
Loader
ExcludeFields []string
infofile string
}
func (self *YTDLLoader) CanHandle(name string) Loader {
if infofile := self.getInfoFilePath(name); infofile != `` {
if _, err := os.Stat(infofile); err == nil {
return &YTDLLoader{
infofile: infofile,
}
}
}
return nil
}
func (self *YTDLLoader) LoadMetadata(name string) (map[string]interface{}, error) {
if self.ExcludeFields == nil {
self.ExcludeFields = DefaultExcludeFields
}
if self.infofile != `` {
return self.parseInfoFile(self.infofile)
}
return nil, nil
}
func (self *YTDLLoader) getInfoFilePath(name string) string {
dir, base := path.Split(name)
ext := path.Ext(base)
if ext != `.json` {
return path.Join(dir, strings.TrimSuffix(base, ext)+`.info.json`)
}
return ``
}
func (self *YTDLLoader) parseInfoFile(name string) (map[string]interface{}, error) {
if file, err := os.Open(name); err == nil {
rv := make(map[string]interface{})
if err := json.NewDecoder(file).Decode(&rv); err == nil {
var duration interface{}
if dSecI := maputil.DeepGet(rv, []string{`duration`}, nil); dSecI != nil {
if dSec, err := stringutil.ConvertToInteger(dSecI); err == nil {
duration = dSec * int64(1000)
}
}
output := map[string]interface{}{
`media`: map[string]interface{}{
`type`: `web`,
`title`: maputil.DeepGet(rv, []string{`title`}, nil),
`description`: maputil.DeepGet(rv, []string{`description`}, nil),
`duration`: duration,
`aired`: func() interface{} {
if v := maputil.DeepGet(rv, []string{`upload_date`}, nil); v != nil {
if vS := fmt.Sprintf("%v", v); len(vS) == 8 {
return vS[0:4] + `-` + vS[4:6] + `-` + vS[6:8]
}
}
return nil
}(),
`rating`: maputil.DeepGet(rv, []string{`average_rating`}, nil),
`thumbnail`: maputil.DeepGet(rv, []string{`thumbnail`}, nil),
},
}
for _, field := range self.ExcludeFields {
maputil.DeepSet(rv, strings.Split(field, `.`), nil)
}
if v, err := maputil.Compact(rv); err == nil {
rv = v
}
output[`ytdl`] = rv
return output, nil
} else {
return nil, fmt.Errorf("Unrecognized ytdl info file format at %q: %v", name, err)
}
} else {
return nil, err
}
}