-
Notifications
You must be signed in to change notification settings - Fork 1
/
chat.go
149 lines (130 loc) · 3.91 KB
/
chat.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
package main
import (
"context"
"fmt"
"time"
"golang.org/x/oauth2"
"google.golang.org/api/option"
"google.golang.org/api/youtube/v3"
)
type MessageType string
const (
ChatEnded MessageType = "chatEndedEvent"
SuperChat MessageType = "superChatEvent"
TextMessage MessageType = "textMessageEvent"
)
type Author struct {
ChannelID string `json:"channelId"`
Name string `json:"name"`
ProfileImageURL string `json:"profileImageUrl"`
IsChatModerator bool `json:"isChatModerator"`
IsChatOwner bool `json:"isChatOwner"`
IsChatSponsor bool `json:"isChatSponsor"`
IsVerified bool `json:"isVerified"`
}
type Message struct {
ID string `json:"id"`
Author *Author `json:"author"`
Text string `json:"text"`
Type MessageType `json:"type"`
}
type MessageList struct {
Items []Message `json:"items"`
}
func pollYoutubeLiveChatMessages(ctx context.Context, tokenSource oauth2.TokenSource, liveID string) (chan MessageList, chan error, error) {
ys, err := youtube.NewService(ctx, option.WithTokenSource(tokenSource))
if err != nil {
return nil, nil, fmt.Errorf("failed to create youtube service client: %v", err)
}
vs := youtube.NewVideosService(ys)
lblc := vs.List("liveStreamingDetails")
vResp, err := lblc.Context(ctx).Id(liveID).Do()
if err != nil {
return nil, nil, fmt.Errorf("failed to get live data (id = %s): %v", liveID, err)
}
if len(vResp.Items) == 0 || vResp.Items[0].LiveStreamingDetails == nil {
return nil, nil, fmt.Errorf("failed to get live data (id = %s)", liveID)
}
chatID := vResp.Items[0].LiveStreamingDetails.ActiveLiveChatId
lcms := youtube.NewLiveChatMessagesService(ys)
lcmlc := lcms.List(chatID, "id,snippet,authorDetails")
chRequest := make(chan requestMessages)
chResult := make(chan resultMessages)
go func() {
chRequest <- requestMessages{}
}()
chMsgList := make(chan MessageList)
chErr := make(chan error)
go func() {
Loop:
for {
select {
case <-ctx.Done():
break Loop
case req := <-chRequest:
go func() {
lcmResp, err := lcmlc.Context(ctx).PageToken(req.nextPageToken).Do()
chResult <- resultMessages{lcmResp, err}
}()
case result := <-chResult:
if result.err != nil {
chErr <- fmt.Errorf("failed to get chat messages (id = %s): %v", chatID, result.err)
break Loop
}
if len(result.lcmResp.Items) > 0 {
chMsgList <- messageListFromResp(result.lcmResp)
}
go func() {
var defaultInterval time.Duration = 5 * time.Second
interval := time.Duration(result.lcmResp.PollingIntervalMillis) * time.Millisecond
if interval < defaultInterval {
interval = defaultInterval
}
time.Sleep(interval)
chRequest <- requestMessages{result.lcmResp.NextPageToken}
}()
}
}
close(chMsgList)
close(chErr)
close(chRequest)
close(chResult)
}()
return chMsgList, chErr, nil
}
type requestMessages struct {
nextPageToken string
}
type resultMessages struct {
lcmResp *youtube.LiveChatMessageListResponse
err error
}
func messageListFromResp(resp *youtube.LiveChatMessageListResponse) MessageList {
var mList MessageList
for _, data := range resp.Items {
switch data.Snippet.Type {
case string(ChatEnded), string(SuperChat), string(TextMessage): // ok
default: // ignore other
continue
}
var author *Author
if data.AuthorDetails != nil {
author = &Author{
ChannelID: data.AuthorDetails.ChannelId,
Name: data.AuthorDetails.DisplayName,
ProfileImageURL: data.AuthorDetails.ProfileImageUrl,
IsChatModerator: data.AuthorDetails.IsChatModerator,
IsChatOwner: data.AuthorDetails.IsChatOwner,
IsChatSponsor: data.AuthorDetails.IsChatSponsor,
IsVerified: data.AuthorDetails.IsVerified,
}
}
mList.Items = append(mList.Items, Message{
ID: data.Id,
Author: author,
Text: data.Snippet.DisplayMessage,
Type: MessageType(data.Snippet.Type),
})
}
return mList
}