-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch_playlist.go
245 lines (208 loc) · 5.92 KB
/
fetch_playlist.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
)
type Video struct {
ID string `json:"id"`
Duration int `json:"duration"` // Duration in seconds
StartTime int `json:"start_time"` // Start time in seconds
}
type Playlist struct {
Videos []Video `json:"videos"`
}
type PlaylistItemsResponse struct {
Items []struct {
ContentDetails struct {
VideoID string `json:"videoId"`
} `json:"contentDetails"`
} `json:"items"`
NextPageToken string `json:"nextPageToken"`
}
type VideoDetailsResponse struct {
Items []struct {
ContentDetails struct {
Duration string `json:"duration"`
Definition string `json:"definition"`
RegionRestriction *struct {
Blocked []string `json:"blocked"`
Allowed []string `json:"allowed"`
} `json:"regionRestriction"`
} `json:"contentDetails"`
Status struct {
Embeddable bool `json:"embeddable"`
} `json:"status"`
} `json:"items"`
}
const (
youtubeAPIBaseURL = "https://www.googleapis.com/youtube/v3"
)
func main() {
apiKey := os.Getenv("YT_API_KEY")
if apiKey == "" {
log.Fatal("YT_API_KEY environment variable is not set")
}
playlistIDs := strings.Split(os.Getenv("YT_PLAYLISTS"), ",")
if len(playlistIDs) == 0 || playlistIDs[0] == "" {
log.Fatal("YT_PLAYLISTS environment variable is not set or is empty")
}
var allVideos []Video
for _, playlistID := range playlistIDs {
videos, err := getPlaylistItems(playlistID, apiKey)
if err != nil {
log.Printf("Error getting videos for playlist %s: %v", playlistID, err)
continue
}
allVideos = append(allVideos, videos...)
}
calculateStartTimes(allVideos)
playlist := Playlist{Videos: allVideos}
jsonData, err := json.MarshalIndent(playlist, "", " ")
if err != nil {
log.Fatalf("Error marshaling JSON: %v", err)
}
err = ioutil.WriteFile("docs/playlist.json", jsonData, 0644)
if err != nil {
log.Fatalf("Error writing JSON file: %v", err)
}
fmt.Printf("Updated playlist with %d video details has been stored in playlist.json\n", len(allVideos))
}
func getPlaylistItems(playlistID, apiKey string) ([]Video, error) {
var videos []Video
pageToken := ""
for {
u, _ := url.Parse(youtubeAPIBaseURL + "/playlistItems")
q := u.Query()
q.Set("part", "contentDetails")
q.Set("playlistId", playlistID)
q.Set("maxResults", "50")
q.Set("key", apiKey)
if pageToken != "" {
q.Set("pageToken", pageToken)
}
u.RawQuery = q.Encode()
resp, err := http.Get(u.String())
if err != nil {
return nil, fmt.Errorf("error fetching playlist items: %v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %v", err)
}
// Check if the response is not JSON
if !json.Valid(body) {
return nil, fmt.Errorf("invalid JSON response: %s", string(body))
}
var playlistResp PlaylistItemsResponse
err = json.Unmarshal(body, &playlistResp)
if err != nil {
return nil, fmt.Errorf("error unmarshaling response: %v\nResponse body: %s", err, string(body))
}
for _, item := range playlistResp.Items {
video, err := getVideoDetails(item.ContentDetails.VideoID, apiKey)
if err != nil {
log.Printf("Error getting details for video %s: %v. Skipping.", item.ContentDetails.VideoID, err)
continue
}
if video != nil {
videos = append(videos, *video)
fmt.Printf("Added video %s with duration %d seconds.\n", video.ID, video.Duration)
} else {
fmt.Printf("Skipped video %s (doesn't meet requirements)\n", item.ContentDetails.VideoID)
}
}
pageToken = playlistResp.NextPageToken
if pageToken == "" {
break
}
}
return videos, nil
}
func getVideoDetails(videoID, apiKey string) (*Video, error) {
u, _ := url.Parse(youtubeAPIBaseURL + "/videos")
q := u.Query()
q.Set("part", "contentDetails,status")
q.Set("id", videoID)
q.Set("key", apiKey)
u.RawQuery = q.Encode()
resp, err := http.Get(u.String())
if err != nil {
return nil, fmt.Errorf("error fetching video details: %v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %v", err)
}
if !json.Valid(body) {
return nil, fmt.Errorf("invalid JSON response: %s", string(body))
}
var videoResp VideoDetailsResponse
err = json.Unmarshal(body, &videoResp)
if err != nil {
return nil, fmt.Errorf("error unmarshaling response: %v\nResponse body: %s", err, string(body))
}
if len(videoResp.Items) == 0 {
return nil, fmt.Errorf("no video found with ID %s", videoID)
}
item := videoResp.Items[0]
duration, err := parseDuration(item.ContentDetails.Duration)
if err != nil {
return nil, fmt.Errorf("error parsing duration: %v", err)
}
isEmbeddable := item.Status.Embeddable
isHD := item.ContentDetails.Definition == "hd"
// Check if video has any region restrictions
hasRegionRestrictions := item.ContentDetails.RegionRestriction != nil
// Skip videos that don't meet our criteria
if !isHD || !isEmbeddable || hasRegionRestrictions {
log.Printf("Skipping video %s - HD: %v, Embeddable: %v, Has Region Restrictions: %v",
videoID, isHD, isEmbeddable, hasRegionRestrictions)
return nil, nil
}
return &Video{
ID: videoID,
Duration: duration,
}, nil
}
func parseDuration(duration string) (int, error) {
duration = strings.TrimPrefix(duration, "PT")
seconds := 0
var number string
for _, char := range duration {
switch char {
case 'H':
hours, _ := strconv.Atoi(number)
seconds += hours * 3600
number = ""
case 'M':
minutes, _ := strconv.Atoi(number)
seconds += minutes * 60
number = ""
case 'S':
s, _ := strconv.Atoi(number)
seconds += s
number = ""
default:
number += string(char)
}
}
return seconds, nil
}
func calculateStartTimes(videos []Video) {
currentStartTime := 0
for i := range videos {
videos[i].StartTime = currentStartTime
if i < len(videos)-1 {
currentStartTime += videos[i].Duration
}
}
}