forked from g8rswimmer/go-twitter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tweet_stream.go
339 lines (300 loc) · 7.82 KB
/
tweet_stream.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
package twitter
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"sync"
"time"
)
// SystemMessageType stream system message types
type SystemMessageType string
// StreamErrorType is the type of streaming error
type StreamErrorType string
const (
// InfoMessageType is the information system message type
InfoMessageType SystemMessageType = "info"
// WarnMessageType is the warning system message type
WarnMessageType SystemMessageType = "warn"
// ErrorMessageType is the error system message type
ErrorMessageType SystemMessageType = "error"
tweetStart = "data"
keepAliveTO = 21 * time.Second
// TweetErrorType represents the tweet stream errors
TweetErrorType StreamErrorType = "tweet"
// SystemErrorType represents the system stream errors
SystemErrorType StreamErrorType = "system"
)
// TweetSampleStreamOpts are the options for sample tweet stream
type TweetSampleStreamOpts struct {
BackfillMinutes int
Expansions []Expansion
MediaFields []MediaField
PlaceFields []PlaceField
PollFields []PollField
TweetFields []TweetField
UserFields []UserField
}
func (t TweetSampleStreamOpts) addQuery(req *http.Request) {
q := req.URL.Query()
if len(t.Expansions) > 0 {
q.Add("expansions", strings.Join(expansionStringArray(t.Expansions), ","))
}
if len(t.MediaFields) > 0 {
q.Add("media.fields", strings.Join(mediaFieldStringArray(t.MediaFields), ","))
}
if len(t.PlaceFields) > 0 {
q.Add("place.fields", strings.Join(placeFieldStringArray(t.PlaceFields), ","))
}
if len(t.PollFields) > 0 {
q.Add("poll.fields", strings.Join(pollFieldStringArray(t.PollFields), ","))
}
if len(t.TweetFields) > 0 {
q.Add("tweet.fields", strings.Join(tweetFieldStringArray(t.TweetFields), ","))
}
if len(t.UserFields) > 0 {
q.Add("user.fields", strings.Join(userFieldStringArray(t.UserFields), ","))
}
if t.BackfillMinutes > 0 {
q.Add("backfill_minutes", strconv.Itoa(t.BackfillMinutes))
}
if len(q) > 0 {
req.URL.RawQuery = q.Encode()
}
}
// TweetSearchStreamOpts are the options for the search stream
type TweetSearchStreamOpts struct {
BackfillMinutes int
Expansions []Expansion
MediaFields []MediaField
PlaceFields []PlaceField
PollFields []PollField
TweetFields []TweetField
UserFields []UserField
}
func (t TweetSearchStreamOpts) addQuery(req *http.Request) {
q := req.URL.Query()
if len(t.Expansions) > 0 {
q.Add("expansions", strings.Join(expansionStringArray(t.Expansions), ","))
}
if len(t.MediaFields) > 0 {
q.Add("media.fields", strings.Join(mediaFieldStringArray(t.MediaFields), ","))
}
if len(t.PlaceFields) > 0 {
q.Add("place.fields", strings.Join(placeFieldStringArray(t.PlaceFields), ","))
}
if len(t.PollFields) > 0 {
q.Add("poll.fields", strings.Join(pollFieldStringArray(t.PollFields), ","))
}
if len(t.TweetFields) > 0 {
q.Add("tweet.fields", strings.Join(tweetFieldStringArray(t.TweetFields), ","))
}
if len(t.UserFields) > 0 {
q.Add("user.fields", strings.Join(userFieldStringArray(t.UserFields), ","))
}
if t.BackfillMinutes > 0 {
q.Add("backfill_minutes", strconv.Itoa(t.BackfillMinutes))
}
if len(q) > 0 {
req.URL.RawQuery = q.Encode()
}
}
// StreamError is the error from the streaming
type StreamError struct {
Type StreamErrorType
Msg string
Err error
}
func (e StreamError) Error() string {
msg := fmt.Sprintf("%s: %s", e.Type, e.Msg)
if e.Err == nil {
return msg
}
return fmt.Sprintf("%s %s", msg, e.Err.Error())
}
// Is will compare the error against the stream error and type
func (e *StreamError) Is(target error) bool {
cmp, ok := target.(*StreamError)
if !ok {
return false
}
return cmp.Type == e.Type
}
// Unwrap will return any error associated
func (e *StreamError) Unwrap() error {
return e.Err
}
// TweetMessage is the tweet stream message
type TweetMessage struct {
Raw *TweetRaw
}
// SystemMessage is the system stream message
type SystemMessage struct {
Message string `json:"message"`
Sent time.Time `json:"sent"`
}
// TweetStream is the stream handler
type TweetStream struct {
tweets chan *TweetMessage
system chan map[SystemMessageType]SystemMessage
close chan bool
needReConnect bool
err chan error
alive bool
mutex sync.RWMutex
RateLimit *RateLimit
}
// StartTweetStream will start the tweet streaming
func StartTweetStream(stream io.ReadCloser) *TweetStream {
ts := &TweetStream{
tweets: make(chan *TweetMessage, 10),
system: make(chan map[SystemMessageType]SystemMessage, 10),
close: make(chan bool),
err: make(chan error, 10),
mutex: sync.RWMutex{},
alive: true,
needReConnect: false,
}
go ts.handle(stream)
return ts
}
func (ts *TweetStream) NeedReConnect() bool {
return ts.needReConnect
}
func (ts *TweetStream) heartbeat(beat bool) {
ts.mutex.Lock()
defer ts.mutex.Unlock()
ts.alive = beat
}
// Connection returns if the connect is still alive
func (ts *TweetStream) Connection() bool {
ts.mutex.RLock()
defer ts.mutex.RUnlock()
return ts.alive
}
func (ts *TweetStream) handle(stream io.ReadCloser) {
defer stream.Close()
defer close(ts.tweets)
defer close(ts.system)
defer close(ts.close)
defer close(ts.err)
scanner := bufio.NewScanner(stream)
scanner.Split(streamSeparator)
timer := time.NewTimer(keepAliveTO)
for {
select {
case <-ts.close:
return
case <-timer.C:
ts.heartbeat(false)
default:
}
if !scanner.Scan() {
if scanner.Err() != nil {
go ts.Close()
if err := stream.Close(); err != nil {
ts.err <- err
}
ts.err <- scanner.Err()
ts.needReConnect = true
}
time.Sleep(time.Millisecond * 200)
continue
}
timer.Stop()
timer.Reset(keepAliveTO)
ts.heartbeat(true)
msg := scanner.Bytes()
if len(msg) == 0 {
continue
}
msgMap := map[string]interface{}{}
if err := json.Unmarshal(msg, &msgMap); err != nil {
select {
case ts.err <- fmt.Errorf("stream error: unmarshal error %w", err):
default:
}
continue
}
if _, tweet := msgMap[tweetStart]; tweet {
single := &tweetraw{}
if err := json.Unmarshal(msg, single); err != nil {
sErr := &StreamError{
Type: TweetErrorType,
Msg: "unmarshal tweet stream",
Err: err,
}
select {
case ts.err <- sErr:
ts.needReConnect = true
default:
}
continue
}
raw := &TweetRaw{}
raw.Tweets = make([]*TweetObj, 1)
raw.Tweets[0] = single.Tweet
raw.Includes = single.Includes
raw.Errors = single.Errors
raw.MatchingRules = single.MatchingRules
tweetMsg := &TweetMessage{
Raw: raw,
}
select {
case ts.tweets <- tweetMsg:
default:
}
continue
}
sysMsg := map[SystemMessageType]SystemMessage{}
if err := json.Unmarshal(msg, &sysMsg); err != nil {
sErr := &StreamError{
Type: SystemErrorType,
Msg: "unmarshal system stream",
Err: err,
}
select {
case ts.err <- sErr:
ts.needReConnect = true
default:
}
continue
}
select {
case ts.system <- sysMsg:
default:
}
}
}
// Tweets will return the channel to receive tweet stream messages
func (ts *TweetStream) Tweets() <-chan *TweetMessage {
return ts.tweets
}
// SystemMessages will return the channel to receive system stream messages
func (ts *TweetStream) SystemMessages() <-chan map[SystemMessageType]SystemMessage {
return ts.system
}
// Err will return the channel to receive any stream errors
func (ts *TweetStream) Err() <-chan error {
return ts.err
}
// Close will close the stream and all channels
func (ts *TweetStream) Close() {
ts.close <- true
}
func streamSeparator(data []byte, atEOF bool) (int, []byte, error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if idx := bytes.Index(data, []byte("\r\n")); idx != -1 {
return idx + len("\r\n"), data[0:idx], nil
}
if atEOF {
return len(data), data, nil
}
return 0, nil, nil
}