-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.go
100 lines (84 loc) · 2.62 KB
/
channel.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
package client
import (
"context"
"encoding/json"
_errors "errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"github.com/rl404/fairy/errors/stack"
"github.com/rl404/shimakaze/internal/domain/youtube/entity"
"github.com/rl404/shimakaze/internal/errors"
)
type getChannelsByIDsResponse struct {
PageInfo struct {
TotalResults int `json:"totalResults"`
} `json:"pageInfo"`
Items []struct {
ID string `json:"id"`
Snippet struct {
Title string `json:"title"`
Thumbnails channelThumbnails `json:"thumbnails"`
} `json:"snippet"`
Statistics struct {
SubscriberCount string `json:"subscriberCount"`
} `json:"statistics"`
} `json:"items"`
}
type channelThumbnails struct {
Default thumbnail `json:"default"`
Medium thumbnail `json:"medium"`
}
type thumbnail struct {
URL string `json:"url"`
}
// GetChannelByID to get channel by id.
func (c *Client) GetChannelByID(ctx context.Context, id string) (*entity.Channel, int, error) {
url, _ := url.Parse(fmt.Sprintf("%s/channels", c.host))
q := url.Query()
q.Add("id", id)
q.Add("part", "snippet,contentDetails,statistics")
url.RawQuery = q.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url.String(), nil)
if err != nil {
return nil, http.StatusInternalServerError, stack.Wrap(ctx, err, errors.ErrInternalServer)
}
resp, err := c.http.Do(req)
if err != nil {
return nil, http.StatusInternalServerError, stack.Wrap(ctx, err, errors.ErrInternalServer)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, resp.StatusCode, stack.Wrap(ctx, _errors.New(http.StatusText(resp.StatusCode)))
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, http.StatusInternalServerError, stack.Wrap(ctx, err, errors.ErrInternalServer)
}
var body getChannelsByIDsResponse
if err := json.Unmarshal(respBody, &body); err != nil {
return nil, http.StatusInternalServerError, stack.Wrap(ctx, err, errors.ErrInternalServer)
}
for _, channel := range body.Items {
return &entity.Channel{
ID: channel.ID,
Name: channel.Snippet.Title,
Image: c.getChannelImage(channel.Snippet.Thumbnails),
Subscriber: c.getSubscriber(channel.Statistics.SubscriberCount),
}, http.StatusOK, nil
}
// No need to wrap the error to prevent useless error log.
return nil, http.StatusNotFound, errors.ErrChannelNotFound
}
func (c *Client) getChannelImage(thumbnails channelThumbnails) string {
if thumbnails.Medium.URL != "" {
return thumbnails.Medium.URL
}
return thumbnails.Default.URL
}
func (c *Client) getSubscriber(str string) int {
subs, _ := strconv.Atoi(str)
return subs
}