-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyoutubelive.go
579 lines (525 loc) · 16.6 KB
/
youtubelive.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
package youtubelive
import (
"context"
"errors"
"fmt"
"golang.org/x/oauth2"
"google.golang.org/api/googleapi"
"google.golang.org/api/option"
"google.golang.org/api/youtube/v3"
"log/slog"
"net/http"
"strings"
"sync"
"time"
)
type YouTubeLive struct {
ctx context.Context
closeOnce sync.Once
log *slog.Logger
transport http.RoundTripper
jar http.CookieJar
resolved bool
yclient *ytClient
clientID string
clientSecret string
refreshToken string
listenAddr string
additionalScopes []string
autoAuth bool
onNewRefreshToken func(string)
}
func NewYouTubeLive(clientID, clientSecret string, options ...Option) (*YouTubeLive, error) {
yt := &YouTubeLive{}
yt.ctx = context.Background()
yt.log = slog.Default()
yt.clientID = clientID
yt.clientSecret = clientSecret
yt.listenAddr = "127.0.0.1:0"
var errs error
for _, option := range options {
err := option(yt)
if err != nil {
errs = errors.Join(errs, err)
yt.log.Debug("error while processing option", "error", err)
}
}
if errs != nil {
yt.log.Error("error while processing options", "error", errs)
return nil, errs
}
yt.newYtClient()
return yt, nil
}
// CurrentBroadcastIDFromChannelHandle returns the current live broadcastID which cn be used
// for Attach(). If multiple queries for a user's broadcast is required, to optimize quota usage it is recommended to get the channelID first from
// the channel handle and call CurrentBroadcastIDFromChannelID for this query. Will return NotLiveError when broadcast ID isn't found.
func (yt *YouTubeLive) CurrentBroadcastIDFromChannelHandle(channelName string) (string, error) {
channelID, err := yt.ChannelIDFromChannelHandle(channelName)
if err != nil {
return "", err
}
return yt.CurrentBroadcastIDFromChannelID(channelID)
}
// CurrentBroadcastIDFromChannelID returns the current liver broadcastID which can be used for Attach(). Will return NotLiveError when a current live broadcast is not found.
func (yt *YouTubeLive) CurrentBroadcastIDFromChannelID(channelID string) (string, error) {
err := yt.yclient.refresh()
if err != nil {
return "", err
}
channelsResp, err := yt.yclient.service.Channels.List([]string{"contentDetails"}).
Id(channelID).
Do()
err = wrapOauthErrors(err)
if err != nil {
return "", fmt.Errorf("failed to get channel details: %v", err)
}
if len(channelsResp.Items) == 0 {
return "", errors.New("channel not found")
}
uploadsPlaylist := channelsResp.Items[0].ContentDetails.RelatedPlaylists.Uploads
playlistResp, err := yt.yclient.service.PlaylistItems.List([]string{"contentDetails"}).
PlaylistId(uploadsPlaylist).
MaxResults(50). // Check last 5 videos
Do()
err = wrapOauthErrors(err)
if err != nil {
return "", fmt.Errorf("failed to get uploads: %v", err)
}
for _, item := range playlistResp.Items {
videoID := item.ContentDetails.VideoId
videoResp, err := yt.yclient.service.Videos.List([]string{"liveStreamingDetails"}).
Id(videoID).
Do()
err = wrapOauthErrors(err)
if err != nil || len(videoResp.Items) == 0 {
continue
}
details := videoResp.Items[0].LiveStreamingDetails
if details != nil && details.ActualStartTime != "" && details.ActualEndTime == "" {
return videoID, nil
}
}
// The above works most of the time and is cheaper than a search, and search sometimes doesn't work when the authenticated
// user is not the owner and subscriber only chat. Anyway, fallback to search now and if it still doesn't work there isn't
// currently a known workaround through the API.
qResp, err := yt.yclient.service.Search.List([]string{"snippet", "id"}).
ChannelId(channelID).
EventType("live").
Q(channelID).
Type("video").
Do()
err = wrapOauthErrors(err)
if err != nil {
return "", fmt.Errorf("failed to get search results: %v", err)
}
if len(qResp.Items) == 0 {
return "", NotLiveError
}
return qResp.Items[0].Id.VideoId, nil
}
func (yt *YouTubeLive) CurrentBroadcastIDFromChannelIDB(channelID string) (string, error) {
err := yt.yclient.refresh()
if err != nil {
return "", err
}
resp, err := yt.yclient.service.Search.List([]string{"id"}).ChannelId(channelID).EventType("live").Type("video").Do()
err = wrapOauthErrors(err)
if err != nil {
return "", err
}
if len(resp.Items) == 0 {
return "", NotLiveError
}
return resp.Items[0].Id.VideoId, nil
}
func (yt *YouTubeLive) ChannelIDFromChannelHandle(channelName string) (string, error) {
if len(channelName) < 1 {
return "", InvalidYouTubeChannelName
}
if channelName[0] != '@' {
channelName = "@" + channelName
}
err := yt.yclient.refresh()
if err != nil {
return "", err
}
resp, err := yt.yclient.service.Channels.List([]string{"id"}).ForHandle(channelName).Do()
if err := wrapOauthErrors(err); err != nil {
return "", err
}
if len(resp.Items) == 0 {
return "", fmt.Errorf("user does not exist")
}
return resp.Items[0].Id, nil
}
// IsLive will return true when channel is live.
func (yt *YouTubeLive) IsLive(channelID string) (bool, error) {
if _, err := yt.CurrentBroadcastIDFromChannelID(channelID); err != nil {
if errors.Is(err, NotLiveError) {
return false, nil
}
return false, wrapOauthErrors(err)
}
return true, nil
}
// Attach to a live broadcast. The returned out channel are all live events and the input channel are for chat events to send to broadcast. A closed LiveEvent out channel indicates the live broadcast has ended or an error occurred which would require another Attach. By closing the in BotEvent channel, this will the close sending side of the attached connection but the ctx parameter must be canceled to trigger full cleanup of the attached routines.
func (yt *YouTubeLive) Attach(ctx context.Context, broadcastID string) (<-chan LiveEvent, chan<- BotEvent, error) {
err := yt.yclient.refresh()
if err != nil {
return nil, nil, err
}
liveChatID, err := yt.getLiveChatID(broadcastID)
if err != nil {
return nil, nil, err
}
outChan := make(chan LiveEvent, 100)
inChan := make(chan BotEvent, 100)
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(ctx)
wg.Add(1)
go func() {
defer wg.Done()
defer close(outChan)
yt.pollLiveChat(ctx, liveChatID, outChan)
}()
wg.Add(1)
go func() {
defer wg.Done()
yt.handleBotEvents(ctx, liveChatID, inChan, outChan)
}()
go func() {
<-ctx.Done()
cancel()
wg.Wait()
}()
return outChan, inChan, nil
}
func (yt *YouTubeLive) getLiveChatID(broadcastID string) (string, error) {
call := yt.yclient.service.Videos.List([]string{"liveStreamingDetails"}).
Id(broadcastID).
MaxResults(1)
resp, err := call.Do()
err = wrapOauthErrors(err)
if err != nil {
return "", fmt.Errorf("failed to get broadcast: %w", err)
}
if len(resp.Items) == 0 {
return "", ErrBroadcastNotFound
}
liveChatID := resp.Items[0].LiveStreamingDetails.ActiveLiveChatId
if liveChatID == "" {
return "", ErrChatDisabled
}
return liveChatID, nil
}
func (yt *YouTubeLive) pollLiveChat(ctx context.Context, liveChatID string, out chan<- LiveEvent) {
var (
nextPageToken string
pollInterval = 3 * time.Second // Initial default
forceFirstPoll = true
)
for {
timer := time.NewTimer(pollInterval)
if forceFirstPoll {
timer.Stop() // Immediate first poll
forceFirstPoll = false
}
select {
case <-ctx.Done():
return
case <-time.After(pollInterval):
resp, err := yt.yclient.service.LiveChatMessages.List(liveChatID, []string{"snippet", "authorDetails"}).
PageToken(nextPageToken).
Do()
err = wrapOauthErrors(err)
if err != nil {
yt.log.Debug("live chat poll failed", "error", err)
gerr := &googleapi.Error{}
if errors.As(err, &gerr) {
// TODO make the return behavior optional
select {
case out <- &ErrorEvent{
Timestamp: time.Now().UTC(),
Error: gerr,
}:
case <-ctx.Done():
}
select {
case out <- &ChatEndedEvent{
Timestamp: time.Now().UTC(),
}:
case <-ctx.Done():
}
return
}
// TODO make the return behavior optional
select {
case out <- &ErrorEvent{
Timestamp: time.Now().UTC(),
Error: err,
}:
case <-ctx.Done():
}
continue
}
nextPageToken = resp.NextPageToken
if resp.PollingIntervalMillis > 0 {
pollInterval = time.Duration(resp.PollingIntervalMillis) * time.Millisecond
}
for _, msg := range resp.Items {
event, err := yt.parseChatMessage(msg, resp.NextPageToken)
if err != nil {
yt.log.Warn("failed to parse chat message", "error", err)
continue
}
select {
case out <- event:
case <-ctx.Done():
}
if _, ok := event.(*ChatEndedEvent); ok {
return
}
}
}
}
}
func (yt *YouTubeLive) parseChatMessage(msg *youtube.LiveChatMessage, nextPageToken string) (LiveEvent, error) {
snippet := msg.Snippet
ts, err := time.Parse(time.RFC3339, snippet.PublishedAt)
if err != nil {
return nil, fmt.Errorf("invalid timestamp: %w", err)
}
baseEvent := struct {
NextPageToken string
Timestamp time.Time
DisplayName string
AuthorDetails *youtube.LiveChatMessageAuthorDetails
}{
NextPageToken: nextPageToken,
Timestamp: ts,
DisplayName: msg.AuthorDetails.DisplayName,
AuthorDetails: msg.AuthorDetails,
}
switch snippet.Type {
case "textMessageEvent":
return &ChatMessageEvent{
Message: snippet.TextMessageDetails.MessageText,
DisplayName: baseEvent.DisplayName,
AuthorDetails: toAuthorDetails(baseEvent.AuthorDetails),
Timestamp: baseEvent.Timestamp,
NextPageToken: baseEvent.NextPageToken,
}, nil
case "superChatEvent":
return &SuperChatEvent{
Message: snippet.SuperChatDetails.UserComment,
Amount: float64(snippet.SuperChatDetails.AmountMicros) / 1000000,
Currency: snippet.SuperChatDetails.Currency,
DisplayName: baseEvent.DisplayName,
AuthorDetails: toAuthorDetails(baseEvent.AuthorDetails),
Timestamp: baseEvent.Timestamp,
NextPageToken: baseEvent.NextPageToken,
}, nil
case "superStickerEvent":
return &SuperStickerEvent{
StickerID: snippet.SuperStickerDetails.SuperStickerMetadata.StickerId,
Amount: float64(snippet.SuperStickerDetails.AmountMicros) / 1000000,
Currency: snippet.SuperStickerDetails.Currency,
DisplayName: baseEvent.DisplayName,
AuthorDetails: toAuthorDetails(baseEvent.AuthorDetails),
Timestamp: baseEvent.Timestamp,
NextPageToken: baseEvent.NextPageToken,
}, nil
case "memberMilestoneChatEvent":
return &MemberMilestoneEvent{
DisplayName: baseEvent.DisplayName,
AuthorDetails: toAuthorDetails(baseEvent.AuthorDetails),
Level: strings.ToLower(snippet.MemberMilestoneChatDetails.MemberLevelName),
Months: int(snippet.MemberMilestoneChatDetails.MemberMonth),
Timestamp: baseEvent.Timestamp,
NextPageToken: baseEvent.NextPageToken,
}, nil
case "membershipGiftingEvent":
return &MembershipGiftEvent{
DisplayName: baseEvent.DisplayName,
AuthorDetails: toAuthorDetails(baseEvent.AuthorDetails),
Total: int(snippet.MembershipGiftingDetails.GiftMembershipsCount),
Tier: snippet.MembershipGiftingDetails.GiftMembershipsLevelName,
Timestamp: baseEvent.Timestamp,
NextPageToken: baseEvent.NextPageToken,
}, nil
case "giftMembershipReceivedEvent":
return &MembershipGiftReceivedEvent{
DisplayText: msg.Snippet.DisplayMessage,
Level: msg.Snippet.GiftMembershipReceivedDetails.MemberLevelName,
GifterID: msg.Snippet.GiftMembershipReceivedDetails.GifterChannelId,
Timestamp: baseEvent.Timestamp,
}, nil
case "userBannedEvent":
details := snippet.UserBannedDetails
if details == nil {
return nil, errors.New("moderation event without details")
}
banType := "unknown"
var duration time.Duration
switch {
case details.BanType == "PERMANENT":
banType = "permanent"
case details.BanType == "TEMPORARY":
banType = "temporary"
duration = time.Duration(details.BanDurationSeconds) * time.Second
}
return &UserBannedEvent{
BannedUserID: details.BannedUserDetails.ChannelId,
BannedUserDisplayName: details.BannedUserDetails.DisplayName,
BanType: banType,
Duration: duration,
ModeratorID: snippet.AuthorChannelId,
ModeratorDisplayName: msg.AuthorDetails.DisplayName,
Timestamp: baseEvent.Timestamp,
NextPageToken: baseEvent.NextPageToken,
}, nil
case "chatEndedEvent":
return &ChatEndedEvent{
Timestamp: baseEvent.Timestamp,
NextPageToken: baseEvent.NextPageToken,
}, nil
default:
yt.log.Warn("unsupported message type",
"type", snippet.Type,
"message_id", msg.Id,
"display", snippet.DisplayMessage,
)
return nil, fmt.Errorf("unsupported message type: %s", snippet.Type)
}
}
func (yt *YouTubeLive) handleBotEvents(ctx context.Context, liveChatID string, in <-chan BotEvent, out chan<- LiveEvent) {
for {
select {
case <-ctx.Done():
return
case evt, ok := <-in:
if !ok {
return
}
switch e := evt.(type) {
case BotChatMessage:
err := yt.sendChatMessage(liveChatID, e.Message)
if err != nil {
select {
case out <- &ErrorEvent{
Timestamp: time.Now().UTC(),
Error: err,
}:
case <-ctx.Done():
}
}
case BotDeleteMessage:
err := yt.deleteChatMessage(e.MessageID)
if err != nil {
select {
case out <- &ErrorEvent{
Timestamp: time.Now().UTC(),
Error: err,
}:
case <-ctx.Done():
}
}
default:
yt.log.Debug("received unknown bot event type", "type", fmt.Sprintf("%T", evt))
}
}
}
}
func (yt *YouTubeLive) sendChatMessage(liveChatID, message string) error {
msg := &youtube.LiveChatMessage{
Snippet: &youtube.LiveChatMessageSnippet{
LiveChatId: liveChatID,
Type: "textMessageEvent",
TextMessageDetails: &youtube.LiveChatTextMessageDetails{
MessageText: message,
},
},
}
_, err := yt.yclient.service.LiveChatMessages.Insert([]string{"snippet"}, msg).Do()
err = wrapOauthErrors(err)
return err
}
// SetRefreshToken can be called to update the refresh token. This must only be called with no attached instances.
func (yt *YouTubeLive) SetRefreshToken(token string) {
// TODO: Make it so that it doesn't matter if there are attached instances
yt.newYtClient()
yt.refreshToken = token
yt.yclient.refreshToken = token
}
// Login will use the Oauth2 workflow, if required, to login. If refresh token isn't expired this will not do anything.
// with default configuration this will run a browser to complete the login process.
func (yt *YouTubeLive) Login() error {
_, err := yt.yclient.Token()
if err != nil {
return yt.ForceLogin()
}
return nil
}
func (yt *YouTubeLive) ForceLogin() error {
yt.SetRefreshToken("")
// TODO: use custom workflow options when available.
// TODO: Make it so that it doesn't matter if there are attached instances
err := yt.yclient.refresh()
if err != nil {
return err
}
yt.yclient.tokenSource = yt.yclient.createTokenSource("", true)
_, err = yt.yclient.tokenSource.Token()
if err != nil {
return fmt.Errorf("login failed: %w", err)
}
c := oauth2.NewClient(yt.ctx, yt.yclient.tokenSource)
service, err := youtube.NewService(yt.ctx, option.WithHTTPClient(c))
if err != nil {
return err
}
yt.yclient.service = service
if yt.onNewRefreshToken != nil {
yt.onNewRefreshToken(yt.refreshToken)
}
return nil
}
func (yt *YouTubeLive) deleteChatMessage(messageID string) error {
return wrapOauthErrors(yt.yclient.service.LiveChatMessages.Delete(messageID).Do())
}
func (yt *YouTubeLive) newYtClient() {
lResolver := listenResolve{listenAddr: yt.listenAddr}
if yt.yclient != nil {
// So we don't open the port an extra time
lResolver = yt.yclient.listenR
}
yt.yclient = &ytClient{
ctx: yt.ctx,
transport: yt.transport,
jar: yt.jar,
log: yt.log,
clientID: yt.clientID,
clientSecret: yt.clientSecret,
listenR: lResolver,
// ordering matters due to a workaround for a rare use case, perhaps add an
// OverrideScopes() option in the future for this use case instead.
scopes: append(append(yt.additionalScopes[:0:0], yt.additionalScopes...), requiredScopes...),
refreshToken: yt.refreshToken,
onNewRefreshToken: yt.onNewRefreshToken,
autoAuth: yt.autoAuth,
service: nil,
}
}
func toAuthorDetails(authorDetails *youtube.LiveChatMessageAuthorDetails) AuthorDetails {
return AuthorDetails{
ChannelId: authorDetails.ChannelId,
ChannelUrl: authorDetails.ChannelUrl,
DisplayName: authorDetails.DisplayName,
IsChatModerator: authorDetails.IsChatModerator,
IsChatOwner: authorDetails.IsChatOwner,
IsChatSponsor: authorDetails.IsChatSponsor,
IsVerified: authorDetails.IsVerified,
ProfileImageUrl: authorDetails.ProfileImageUrl,
}
}