-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyoutube.go
72 lines (58 loc) · 1.68 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
package content
import (
"context"
"fmt"
"google.golang.org/api/option"
"google.golang.org/api/youtube/v3"
"io"
"net/url"
"strings"
)
// TODO breadchris API tokens don't seem to work for this API anymore, figure out why
// GetYouTubeTranscript fetches the transcript for the specified video ID.
func GetYouTubeTranscript(videoID string, apiKey string) (string, error) {
// Set up the YouTube API client
ctx := context.Background()
youtubeService, err := youtube.NewService(ctx, option.WithAPIKey(apiKey))
if err != nil {
return "", fmt.Errorf("failed to create YouTube client: %v", err)
}
// Fetch the video caption track
captions, err := youtubeService.Captions.List([]string{"snippet"}, videoID).Do()
if err != nil {
return "", fmt.Errorf("failed to get captions: %v", err)
}
// Check if the video has captions
if len(captions.Items) == 0 {
return "", fmt.Errorf("video has no captions")
}
// Fetch the caption track content
download, err := youtubeService.Captions.Download(captions.Items[0].Id).Download()
if err != nil {
return "", fmt.Errorf("failed to download caption track: %v", err)
}
downloadBytes, err := io.ReadAll(download.Body)
if err != nil {
return "", fmt.Errorf("failed to read caption track: %v", err)
}
captionTrack := string(downloadBytes)
// Return the caption track content as a string
return captionTrack, nil
}
func ExtractVideoID(ytURL string) string {
parsedURL, err := url.Parse(ytURL)
if err != nil {
return ""
}
if parsedURL.Host != "www.youtube.com" {
return ""
}
if parsedURL.Path != "/watch" {
return ""
}
query := parsedURL.Query()
if query.Get("v") == "" {
return ""
}
return strings.TrimSpace(query.Get("v"))
}