-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyoutube.go
187 lines (152 loc) · 4.64 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
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
package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"sort"
"strings"
"github.com/kkdai/youtube/v2"
)
// ErrNoAudio is returned when no suitable audio formats are found for a YouTube video.
var ErrNoAudio = errors.New("no audio formats found")
// YouTubeVideo is a YouTube video that provides audio files to the podcast feed.
type YouTubeVideo struct {
c youtube.Client
videoID string
log *log.Logger
}
// YouTubeProvider is a YouTube video that provides audio files to the podcast feed.
type YouTubeProvider struct{}
// NewYouTubeProvider creates a new YouTubeProvider instance.
func (yt *YouTubeProvider) Name() string {
return "YouTube video"
}
// HandleRequest handles a request for a YouTube video.
func (yt *YouTubeProvider) HandleRequest(w http.ResponseWriter, req *http.Request) audioSource {
u := req.FormValue("url")
if u == "" {
http.Error(w, "missing url= parameter", http.StatusBadRequest)
return nil
}
id, err := extractYouTubeID(u)
if err != nil {
http.Error(w, "failed to parse YouTube video URL: "+err.Error(), http.StatusBadRequest)
return nil
}
redirectURL := u
if ref := req.Referer(); ref != "" { // added via the UI form field
redirectURL = ref
}
// return the podcast item first, then redirect to the original URL
defer http.Redirect(w, req, redirectURL, http.StatusSeeOther)
return NewYouTubeVideo(id)
}
func extractYouTubeID(s string) (string, error) {
u, err := url.Parse(s)
if err != nil {
return "", fmt.Errorf("failed to parse YouTube link: %w", err)
}
id := u.Query().Get("v")
if id == "" {
return "", fmt.Errorf("unsupported YouTube link %s", s)
}
return id, nil
}
// NewYouTubeVideo creates a new YouTubeVideo instance.
func NewYouTubeVideo(videoID string) *YouTubeVideo {
return &YouTubeVideo{
videoID: videoID,
log: log.New(log.Writer(), videoID+": ", log.LstdFlags),
}
}
// Metadata returns the metadata for the YouTube video.
func (y *YouTubeVideo) Metadata(ctx context.Context) (Metadata, error) {
video, err := y.c.GetVideoContext(ctx, y.videoID)
if err != nil {
return Metadata{}, fmt.Errorf("failed to get video info: %w", err)
}
_, bestAudio, err := y.bestAudio(ctx)
if err != nil {
return Metadata{}, fmt.Errorf("failed to find audio: %w", err)
}
y.log.Printf("got the best audio stream %s @ %d bps", bestAudio.MimeType, bestAudio.Bitrate)
mimeType := bestAudio.MimeType
if ind := strings.IndexByte(mimeType, ';'); ind >= 0 {
mimeType = mimeType[:ind]
}
return Metadata{
Type: YouTubeItem,
OriginalURL: "https://youtube.com/watch?v=" + y.videoID,
Title: video.Title,
Author: video.Author,
Duration: video.Duration,
MIMEType: mimeType,
ContentLength: bestAudio.ContentLength,
}, nil
}
// DownloadURL returns the URL to download the YouTube video.
func (y *YouTubeVideo) DownloadURL(ctx context.Context) (string, error) {
u, _, err := y.bestAudio(ctx)
return u, err
}
func (y *YouTubeVideo) bestAudio(ctx context.Context) (string, youtube.Format, error) {
video, err := y.c.GetVideoContext(ctx, y.videoID)
if err != nil {
return "", youtube.Format{}, fmt.Errorf("failed to get video info: %w", err)
}
bestAudio, err := pickBestAudio(video.Formats)
if err != nil {
return "", youtube.Format{}, fmt.Errorf("failed to find audio: %w", err)
}
u, err := y.c.GetStreamURLContext(ctx, video, &bestAudio)
if err != nil {
return "", youtube.Format{}, fmt.Errorf("failed to fetch %s stream: %w", bestAudio.MimeType, err)
}
return u, bestAudio, nil
}
func pickBestAudio(formats youtube.FormatList) (youtube.Format, error) {
audio := make(map[string]youtube.FormatList)
for _, format := range formats {
if !strings.HasPrefix(format.MimeType, "audio/") {
continue
}
kv := strings.SplitN(format.MimeType, ";", 2)
audio[kv[0]] = append(audio[kv[0]], format)
}
for _, mimeType := range [...]string{"audio/mp4", "audio/mp3"} {
formats, ok := audio[mimeType]
if !ok || len(formats) == 0 {
continue
}
sort.Slice(formats, func(i, j int) bool {
if formats[i].AudioChannels == formats[j].AudioChannels {
return parseAudioQuality(formats[i].AudioQuality) > parseAudioQuality(formats[j].AudioQuality)
}
return formats[i].AudioChannels > formats[j].AudioChannels
})
return formats[0], nil
}
return youtube.Format{}, ErrNoAudio
}
type audioQuality uint8
const (
unknownQuality audioQuality = iota
lowQuality
mediumQuality
highQuality
)
func parseAudioQuality(s string) audioQuality {
switch s {
case "AUDIO_QUALITY_LOW":
return lowQuality
case "AUDIO_QUALITY_MEDIUM":
return mediumQuality
case "AUDIO_QUALITY_HIGH":
return highQuality
default:
return unknownQuality
}
}