This repository has been archived by the owner on Mar 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
video_comments.go
220 lines (199 loc) · 4.85 KB
/
video_comments.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
package main
import (
"encoding/json"
"fmt"
"os"
"sync"
"time"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
yt "github.com/terorie/ytwrk"
"github.com/terorie/ytwrk/types"
)
var continuationLimitReached = fmt.Errorf("continuation limit reached")
var videoCommentsCmd = cobra.Command{
Use: "comments [video...]",
Short: "Scrape comments of videos",
Args: cobra.ArbitraryArgs,
Run: cmdFunc(doVideoComments),
}
func init() {
f := videoCommentsCmd.Flags()
f.Duration("slow-start", time.Second, "Time to wait between opening connections")
f.String("sort", "new", "Comment sort order (new, top)")
videoCmd.AddCommand(&videoCommentsCmd)
}
func doVideoComments(c *cobra.Command, args []string) error {
flags := c.Flags()
sortOrder, err := flags.GetString("sort")
if err != nil {
panic(err)
}
var top bool
switch sortOrder {
case "new":
top = false
case "top":
top = true
default:
return fmt.Errorf("unknown sort order: %s", sortOrder)
}
start := time.Now()
defer func() {
logrus.Infof("Finished after %s", time.Since(start).String())
}()
// Create argument channels
jobs := make(chan string)
go stdinOrArgs(jobs, args)
videoIDs := make(chan string)
go func() {
defer close(videoIDs)
for job := range jobs {
videoID, err := yt.ExtractVideoID(job)
if err != nil {
logrus.Error(err)
continue
}
videoIDs <- videoID
}
}()
// Dump comments
comments := make(chan types.Comment)
startDelay, err := flags.GetDuration("slow-start")
if err != nil {
panic(err)
}
go videoCommentDumpScheduler(comments, videoIDs, startDelay, top)
enc := json.NewEncoder(os.Stdout)
commentCount := int64(0)
for comment := range comments {
if err := enc.Encode(&comment); err != nil {
return err
}
commentCount++
}
logrus.WithField("count", commentCount).Info("Success")
return nil
}
func videoCommentDumpScheduler(comments chan<- types.Comment, videoIDs <-chan string, startDelay time.Duration, top bool) {
defer close(comments)
var wg sync.WaitGroup
wg.Add(int(maxWorkers))
for i := uint(0); i < maxWorkers; i++ {
go func() {
defer wg.Done()
for videoID := range videoIDs {
logrus.WithField("video_id", videoID).
Info("Start video")
err := streamVideoComments(comments, videoID, top)
if err != nil {
logrus.WithError(err).Errorf("Failed to dump comments of video %s", videoID)
}
}
}()
time.Sleep(startDelay)
}
wg.Wait()
}
func streamVideoComments(comments chan<- types.Comment, videoID string, top bool) error {
videoID, err := yt.ExtractVideoID(videoID)
if err != nil {
return err
}
vid, err := client.RequestVideo(videoID).Do()
if err != nil {
return err
}
cont := yt.InitialCommentContinuation(vid)
if cont == nil {
return fmt.Errorf("failed to request comments")
}
if top {
streamTopComments(comments, cont)
} else {
streamNewComments(comments, cont)
}
return nil
}
func streamComments(comments chan<- types.Comment, cont *types.CommentContinuation, i int) {
var j int
var err error
for {
var page types.CommentPage
page, err = nextCommentPage(cont, i, j)
if err != nil {
break
}
if cont.ParentID != "" {
j++
} else {
i++
}
for _, comment := range page.Comments {
subCont := yt.CommentRepliesContinuation(&comment, cont)
if subCont != nil {
streamComments(comments, subCont, i)
}
comments <- comment
}
if !page.MoreComments {
break
}
}
if err == continuationLimitReached {
logrus.Warn("Continuation limit reached")
} else if err != nil {
logrus.WithError(err).Error("Comment stream aborted")
}
}
func streamNewComments(comments chan<- types.Comment, cont *types.CommentContinuation) {
var err error
var page types.CommentPage
page, err = nextCommentPage(cont, -1, 0)
if err != nil {
logrus.WithError(err).Error("Comment stream aborted")
return
}
if page.NewComments == nil {
return
}
*cont = *page.NewComments
streamComments(comments, cont, 0)
}
func streamTopComments(comments chan<- types.Comment, cont *types.CommentContinuation) {
var err error
var page types.CommentPage
page, err = nextCommentPage(cont, -1, 0)
if err != nil {
logrus.WithError(err).Error("Comment stream aborted")
return
}
if page.NewComments == nil {
return
}
*cont = *page.TopComments
streamComments(comments, cont, 0)
}
func nextCommentPage(cont *types.CommentContinuation, i int, j int) (page types.CommentPage, err error) {
page, err = client.RequestCommentPage(cont).Do()
if err != nil {
return page, err
}
for _, cErr := range page.CommentParseErrs {
logrus.WithError(cErr).Error("Failed to parse comment")
}
if cont.ParentID == "" {
logrus.WithFields(logrus.Fields{
"video_id": cont.VideoID,
"index": i,
}).Infof("Page")
} else {
logrus.WithFields(logrus.Fields{
"video_id": cont.VideoID,
"index": i,
"sub_index": j,
"parent_id": cont.ParentID,
}).Infof("Sub page")
}
return page, nil
}