forked from bwmarrin/disgord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_api.go
246 lines (205 loc) · 7.23 KB
/
data_api.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
246
package youtubesvc
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"regexp"
"time"
"github.com/sirupsen/logrus"
"github.com/w8kerr/delubot/config"
"github.com/w8kerr/delubot/models"
"github.com/w8kerr/delubot/utils"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
"google.golang.org/api/youtube/v3"
)
type UserYoutubeService struct {
service *youtube.Service
log *logrus.Entry
}
func (svc *UserYoutubeService) Service() *youtube.Service {
return svc.service
}
func NewUserYoutubeService(token string, refreshToken *string) (*UserYoutubeService, error) {
ctx := context.Background()
log := logrus.WithField("svc", "YoutubeService")
log.WithField("token", token).WithField("refreshToken", *refreshToken).Info("Initializing user Youtube service")
// Service account based oauth2 two legged integration
tokenObj := &oauth2.Token{
AccessToken: token,
}
if refreshToken != nil {
tokenObj.RefreshToken = *refreshToken
tokenObj.Expiry = time.Now().Add(-10 * time.Minute)
}
log.WithField("token", token).WithField("refreshToken", tokenObj.RefreshToken).Info("Initialized user Youtube service")
credentialsJSON, err := json.Marshal(config.GoogleOauthCredentials)
if err != nil {
log.WithError(err).Error("Failed to initialize service, bad credentials")
return &UserYoutubeService{}, err
}
gConf, err := google.ConfigFromJSON(credentialsJSON, "https://www.googleapis.com/auth/youtube.readonly https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/youtube.force-ssl openid")
if err != nil {
log.WithError(err).Error("Failed to initialize service, bad config")
return &UserYoutubeService{}, err
}
// tokenConf := &oauth2.Config{
// ClientID: config.GoogleClientID,
// ClientSecret: config.GoogleSecret,
// RedirectURL: "https://localhost:3000/v1/auth/google/callback",
// Endpoint: oauth2.Endpoint{
// AuthURL: "https://accounts.google.com/o/oauth2/auth",
// TokenURL: "https://oauth2.googleapis.com/token",
// AuthStyle: oauth2.AuthStyleInParams,
// },
// Scopes: []string{
// "https://www.googleapis.com/auth/youtube.readonly",
// "https://www.googleapis.com/auth/userinfo.profile",
// "https://www.googleapis.com/auth/youtube.force-ssl",
// "openid",
// },
// }
client := gConf.Client(ctx, tokenObj)
service, err := youtube.New(client)
if err != nil {
log.WithError(err).Error("Failed to initialize service")
return &UserYoutubeService{}, err
}
return &UserYoutubeService{
log: log,
service: service,
}, nil
}
func (usvc *UserYoutubeService) SendChatMessage(livechatID string, content string) (*youtube.LiveChatMessage, error) {
msg := &youtube.LiveChatMessage{
Snippet: &youtube.LiveChatMessageSnippet{
LiveChatId: livechatID,
Type: "textMessageEvent",
TextMessageDetails: &youtube.LiveChatTextMessageDetails{
MessageText: content,
},
},
}
sent, err := usvc.service.LiveChatMessages.Insert([]string{"snippet"}, msg).Do()
if err != nil {
log.Printf("Failed to send chat message: %s", err)
log.Println(sent, err)
}
return sent, err
}
type YoutubeService struct {
service *youtube.Service
log *logrus.Entry
}
func NewYoutubeService(ctx context.Context) (*YoutubeService, error) {
credentialsJSON, err := json.Marshal(config.GoogleCredentials)
if err != nil {
log.Printf("Failed to form Google credentials, %s", err)
return &YoutubeService{}, err
}
// fmt.Println(string(credentialsJSON))
// Service account based oauth2 two legged integration
service, err := youtube.NewService(ctx, option.WithCredentialsJSON(credentialsJSON))
if err != nil {
log.Printf("Failed to initialize service, %s", err)
return &YoutubeService{}, err
}
return &YoutubeService{
log: logrus.WithField("svc", "YoutubeService"),
service: service,
}, nil
}
func (svc *YoutubeService) GetStreamInfo(videoID string) (time.Time, *time.Time, *youtube.VideoSnippet, error) {
resp, err := svc.service.Videos.List([]string{"liveStreamingDetails,snippet"}).Id(videoID).Do()
if err != nil {
return time.Time{}, nil, nil, errors.New("Failed to get video info")
}
utils.PrintJSON(resp)
if len(resp.Items) == 0 {
return time.Time{}, nil, nil, errors.New("Video not found")
}
if resp.Items[0].LiveStreamingDetails == nil {
return time.Time{}, nil, nil, errors.New("Video had no stream details")
}
scheduledTimeStr := resp.Items[0].LiveStreamingDetails.ScheduledStartTime
if scheduledTimeStr == "" {
return time.Time{}, nil, nil, errors.New("Stream had no start time")
}
scheduledTime, err := time.Parse(time.RFC3339, scheduledTimeStr)
if err != nil {
return time.Time{}, nil, nil, errors.New("Stream had start time with unexpected format")
}
startTimeStr := resp.Items[0].LiveStreamingDetails.ActualStartTime
if startTimeStr == "" {
return scheduledTime, nil, resp.Items[0].Snippet, nil
}
startTime, err := time.Parse(time.RFC3339, startTimeStr)
if err != nil {
return scheduledTime, nil, resp.Items[0].Snippet, nil
}
return scheduledTime, &startTime, resp.Items[0].Snippet, nil
}
func (svc *YoutubeService) ListUpcomingStreams(channelID string) ([]models.YoutubeStreamRecord, error) {
liveRecs := []models.YoutubeStreamRecord{}
resp, err := svc.service.Search.List([]string{"id,snippet"}).ChannelId("UC7YXqPO3eUnxbJ6rN0z2z1Q").Type("video").EventType("upcoming").Do()
if err != nil {
return liveRecs, err
}
if len(resp.Items) == 0 {
return liveRecs, nil
}
for _, live := range resp.Items {
vids, err := svc.service.Videos.List([]string{"liveStreamingDetails,snippet"}).Id(live.Id.VideoId).Do()
if err != nil {
return liveRecs, err
}
vid := vids.Items[0]
t, _ := time.Parse(time.RFC3339, vid.LiveStreamingDetails.ScheduledStartTime)
rec := models.YoutubeStreamRecord{
PostTitle: vid.Snippet.ChannelTitle,
PostLink: "https://www.youtube.com/watch?v=" + vids.Items[0].Id,
PostPlan: 0,
YoutubeID: vids.Items[0].Id,
Completed: false,
ScheduledTime: t,
StreamTitle: vid.Snippet.Title,
StreamThumbnail: vid.Snippet.Thumbnails.High.Url,
}
liveRecs = append(liveRecs, rec)
}
return liveRecs, nil
}
func (svc *YoutubeService) GetLivechatID(videoID string) (string, string, error) {
resp, err := svc.service.Videos.List([]string{"liveStreamingDetails,snippet"}).Id(videoID).Do()
if err != nil {
return "", "", errors.New("Failed to get video info")
}
if len(resp.Items) == 0 {
return "", "", errors.New("No video")
}
vid := resp.Items[0]
if vid.LiveStreamingDetails.ActiveLiveChatId == "" {
return "", vid.Snippet.Title, errors.New("Video is not live")
}
fmt.Println("LIVE STREAMING DETAILS")
utils.PrintJSON(vid)
return vid.LiveStreamingDetails.ActiveLiveChatId, vid.Snippet.Title, nil
}
var idRE = regexp.MustCompile(`^[^"&?\/\s]{11}$`)
var youtubeRE = regexp.MustCompile(`(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})`)
func (svc *YoutubeService) ParseVideoID(text string) (string, error) {
idMatches := idRE.FindAllStringSubmatch(text, -1)
for _, m := range idMatches {
fmt.Println(m)
return m[0], nil
}
linkMatches := youtubeRE.FindAllStringSubmatch(text, -1)
for _, m := range linkMatches {
fmt.Println(m)
return m[1], nil
}
return "", errors.New("No match")
}