/
youtube.go
81 lines (65 loc) · 1.73 KB
/
youtube.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
package rhema
import (
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"github.com/icza/gox/stringsx"
"github.com/kai5263499/rhema/domain"
pb "github.com/kai5263499/rhema/generated"
"github.com/sirupsen/logrus"
)
var _ domain.Converter = (*YouTube)(nil)
func NewYoutube(cfg *domain.Config, scrape domain.Converter, speedupAudio domain.Converter) *YouTube {
return &YouTube{
cfg: cfg,
scrape: scrape,
speedupAudio: speedupAudio,
execCommand: exec.Command,
}
}
type YouTube struct {
cfg *domain.Config
scrape domain.Converter
speedupAudio domain.Converter
execCommand func(command string, args ...string) *exec.Cmd
}
func (yt *YouTube) Convert(ci *pb.Request) error {
if err := yt.scrape.Convert(ci); err != nil {
logrus.WithFields(logrus.Fields{
"uri": ci.Uri,
"title": ci.Title,
"err": err,
}).Warnf("unable to scrape title")
} else {
if len(ci.Title) > 3 {
ci.Title = stringsx.Clean(ci.Title)
}
}
ci.Type = pb.ContentType_AUDIO
fileName, err := GetFilePath(ci)
if err != nil {
return err
}
mp3FullFilename := filepath.Join(yt.cfg.TmpPath, fileName)
mp3FullFilename = fmt.Sprintf("%s%s", mp3FullFilename[:len(mp3FullFilename)-4], "")
if err := os.MkdirAll(path.Dir(mp3FullFilename), os.ModePerm); err != nil {
return err
}
logrus.Debugf("before execCommand with mp3FullFilename=%s uri=%s", mp3FullFilename, ci.Uri)
youtubeCmd := yt.execCommand("yt-dlp",
"--extract-audio",
"--add-metadata",
"--audio-format", "mp3",
"--restrict-filenames",
"-o", fmt.Sprintf("%s.%%(ext)s", mp3FullFilename),
ci.Uri)
youtubeCmd.Stdout = os.Stdout
youtubeCmd.Stderr = os.Stdout
if err := youtubeCmd.Run(); err != nil {
return err
}
youtubeCmd.Wait()
return nil
}