/
video.go
94 lines (79 loc) · 2.04 KB
/
video.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
package client
import (
"context"
_errors "errors"
"net/http"
"strings"
"time"
"github.com/nicklaw5/helix/v2"
"github.com/rl404/fairy/errors/stack"
"github.com/rl404/shimakaze/internal/domain/twitch/entity"
"github.com/rl404/shimakaze/internal/errors"
"github.com/rl404/shimakaze/internal/utils"
)
// GetVideos to get videos.
func (c *Client) GetVideos(ctx context.Context, id string) ([]entity.Video, int, error) {
if code, err := c.setToken(ctx); err != nil {
return nil, code, stack.Wrap(ctx, err)
}
var res []entity.Video
var cursor string
for {
resp, err := c.client.GetVideos(&helix.VideosParams{
UserID: id,
Type: "archive",
First: 100,
After: cursor,
})
if err != nil {
if resp == nil {
return nil, http.StatusInternalServerError, stack.Wrap(ctx, err, errors.ErrInternalServer)
}
return nil, resp.StatusCode, stack.Wrap(ctx, _errors.New(resp.Error), _errors.New(resp.ErrorMessage))
}
var done bool
for _, v := range resp.Data.Videos {
startDate := c.getStartDate(v.CreatedAt)
if startDate == nil || startDate.Before(c.maxAge) {
done = true
break
}
res = append(res, entity.Video{
ID: v.ID,
Title: v.Title,
URL: v.URL,
Image: c.getVideoImage(v.ThumbnailURL),
StartDate: startDate,
EndDate: c.getEndDate(startDate, v.Duration),
})
}
if len(resp.Data.Videos) < 100 || done {
break
}
cursor = resp.Data.Pagination.Cursor
}
return res, http.StatusOK, nil
}
func (c *Client) getVideoImage(url string) string {
url = strings.ReplaceAll(url, "%{width}", "400")
url = strings.ReplaceAll(url, "%{height}", "200")
return url
}
func (c *Client) getStartDate(d string) *time.Time {
t, err := time.Parse(time.RFC3339, d)
if err != nil {
return nil
}
return &t
}
func (c *Client) getEndDate(startDate *time.Time, dur string) *time.Time {
if startDate == nil {
return nil
}
duration, err := utils.ParseDuration(dur, true)
if err != nil || duration == 0 {
return nil
}
endDate := startDate.Add(duration)
return &endDate
}