-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
64 lines (56 loc) · 2.04 KB
/
client.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
package youtube
import (
"context"
"github.com/colinfike/yougo-premium/internal/config"
"google.golang.org/api/option"
youtubesdk "google.golang.org/api/youtube/v3"
)
type client interface {
listChannels(string) (ChannelInfo, error)
listVideos(string) (ChannelInfo, error)
searchVideos(string, string, int64) ([]VideoInfo, error)
}
// youtubeClient is a wrapper around the youtube API in order to faciliate DI/unit testing of the functions on Wrapper.
// Wrapper barely does anything more than youtubeClient but the exercise is worth it.
type youtubeClient struct {
service *youtubesdk.Service
config *config.Config
}
// NewYoutubeClient is the provider function for the wrapper around the Google Youtube API.
func NewYoutubeClient(c *config.Config) (*youtubeClient, error) {
ctx := context.Background()
youtubeService, err := youtubesdk.NewService(ctx, option.WithAPIKey(c.YoutubeAPIKey))
if err != nil {
return &youtubeClient{}, err
}
return &youtubeClient{youtubeService, c}, err
}
func (yt *youtubeClient) listChannels(channelID string) (ChannelInfo, error) {
resp, err := yt.service.Channels.List("snippet").Id(channelID).Do()
if err != nil || len(resp.Items) == 0 {
return ChannelInfo{}, err
}
return ChannelInfo{resp.Items[0].Id, resp.Items[0].Snippet.Title}, nil
}
func (yt *youtubeClient) listVideos(videoID string) (ChannelInfo, error) {
resp, err := yt.service.Videos.List("snippet").Id(videoID).Do()
if err != nil || len(resp.Items) == 0 {
return ChannelInfo{}, err
}
return ChannelInfo{resp.Items[0].Snippet.ChannelId, resp.Items[0].Snippet.ChannelTitle}, nil
}
func (yt *youtubeClient) searchVideos(channelID string, ts string, maxResults int64) ([]VideoInfo, error) {
req := yt.service.Search.List("snippet").ChannelId(channelID).Order("date").MaxResults(maxResults)
if ts != "" {
req.PublishedAfter(ts)
}
resp, err := req.Do()
if err != nil {
return nil, err
}
videos := make([]VideoInfo, 0)
for _, video := range resp.Items {
videos = append(videos, VideoInfo{video.Id.VideoId, video.Snippet.Title})
}
return videos, nil
}