-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
156 lines (139 loc) · 3.68 KB
/
main.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
package main
import (
"bufio"
"context"
"encoding/csv"
"errors"
"flag"
"fmt"
"html"
"os"
"strconv"
"strings"
"golang.org/x/exp/constraints"
"google.golang.org/api/option"
youtube "google.golang.org/api/youtube/v3"
)
type programInputs struct {
apiKey string
channelId string
publishedBefore string
publishedAfter string
}
type videosResult struct {
Videos []*videoDetails `json:"videos"`
}
type videoDetails struct {
VideoId string `json:"id"`
Title string `json:"title"`
ViewCount uint64 `json:"viewCount"`
}
const maxResults int = 50
func main() {
inputs := getProgramInputs()
ctx := context.Background()
service, err := youtube.NewService(ctx, option.WithAPIKey(inputs.apiKey))
check(err)
result := getVideos(service, inputs)
updateVideoStats(service, &result)
printVideos(result)
// content, _ := json.Marshal(result)
// fmt.Printf(string(content))
}
func getProgramInputs() (result programInputs) {
result.apiKey = os.Getenv("YOUTUBE_APIKEY")
flag.StringVar(&result.channelId, "channel", "", "YouTube Channel ID")
flag.StringVar(&result.publishedBefore, "before", "", "Published before time, i.e. 2019-12-04T00:00:00Z")
flag.StringVar(&result.publishedAfter, "after", "", "Published after time, i.e. 2019-12-03T00:00:00Z")
flag.Parse()
if result.apiKey == "" {
check(errors.New("missing APIKEY environment variable"))
}
if result.channelId == "" {
check(errors.New("missing -channelId argument"))
}
return result
}
func getVideos(service *youtube.Service, inputs programInputs) (result videosResult) {
var nextPageToken string
searchListPart := []string{"snippet"}
for {
call := service.Search.List(searchListPart).
Type("video").
MaxResults(int64(maxResults)).
Order("viewCount").
ChannelId(inputs.channelId)
if inputs.publishedBefore != "" {
call.PublishedBefore(inputs.publishedBefore)
}
if inputs.publishedAfter != "" {
call.PublishedAfter(inputs.publishedAfter)
}
if nextPageToken != "" {
call.PageToken(nextPageToken)
}
response, err := call.Do()
check(err)
for _, item := range response.Items {
result.Videos = append(result.Videos, &videoDetails{
VideoId: item.Id.VideoId,
Title: html.UnescapeString(item.Snippet.Title),
})
}
nextPageToken = response.NextPageToken
if nextPageToken == "" {
break
}
}
return result
}
func updateVideoStats(service *youtube.Service, videoResults *videosResult) {
videoIDs := make([]string, len(videoResults.Videos))
for i, video := range videoResults.Videos {
videoIDs[i] = video.VideoId
}
// Iterate through the video IDs in chunks of maxResults
videosListPart := []string{"statistics"}
for i := 0; i < len(videoIDs); i += maxResults {
videoIDsJoined := strings.Join(videoIDs[i:min(i+maxResults, len(videoIDs))], ",")
videosListCall := service.Videos.List(videosListPart).Id(videoIDsJoined)
videosListResponse, err := videosListCall.Do()
check(err)
// Iterate through the video data and update the view count for each video
for j, video := range videosListResponse.Items {
videoResults.Videos[i+j].ViewCount = video.Statistics.ViewCount
}
}
}
func printVideos(result videosResult) {
writer := csv.NewWriter(bufio.NewWriter(os.Stdout))
headers := []string{
"Views",
"Title",
"URL",
}
err := writer.Write(headers)
check(err)
for _, video := range result.Videos {
row := []string{
strconv.FormatUint(video.ViewCount, 10),
video.Title,
"https://www.youtube.com/watch?v=" + video.VideoId,
}
err := writer.Write(row)
check(err)
}
writer.Flush()
}
func check(err error) {
if err != nil {
fmt.Printf("Error: %s\n", err)
os.Exit(1)
}
}
func min[T constraints.Ordered](a, b T) T {
if a < b {
return a
}
return b
}