-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.go
209 lines (185 loc) · 4.49 KB
/
main.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
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"github.com/kurrik/json"
"github.com/kurrik/oauth1a"
"github.com/kurrik/twittergo"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
)
func LoadCredentials() (client *twittergo.Client, err error) {
credentials, err := ioutil.ReadFile("CREDENTIALS")
if err != nil {
return
}
lines := strings.Split(string(credentials), "\n")
config := &oauth1a.ClientConfig{
ConsumerKey: lines[0],
ConsumerSecret: lines[1],
}
user := oauth1a.NewAuthorizedConfig(lines[2], lines[3])
client = twittergo.NewClient(config, user)
return
}
type Args struct {
Track string
}
func parseArgs() *Args {
a := &Args{}
flag.StringVar(&a.Track, "track", "Data Science,Big Data", "Keyword to look up")
flag.Parse()
return a
}
type streamConn struct {
client *http.Client
resp *http.Response
url *url.URL
stale bool
closed bool
mu sync.Mutex
// wait time before trying to reconnect, this will be
// exponentially moved up until reaching maxWait, when
// it will exit
wait int
maxWait int
connect func() (*http.Response, error)
}
func NewStreamConn(max int) streamConn {
return streamConn{wait: 1, maxWait: max}
}
func (conn *streamConn) Close() {
// Just mark the connection as stale, and let the connect() handler close after a read
conn.mu.Lock()
defer conn.mu.Unlock()
conn.stale = true
conn.closed = true
if conn.resp != nil {
conn.resp.Body.Close()
}
}
func (conn *streamConn) isStale() bool {
conn.mu.Lock()
r := conn.stale
conn.mu.Unlock()
return r
}
func readStream(client *twittergo.Client, sc streamConn, path string, query url.Values,
resp *twittergo.APIResponse, handler func([]byte), done chan bool) {
var reader *bufio.Reader
reader = bufio.NewReader(resp.Body)
for {
//we've been closed
if sc.isStale() {
sc.Close()
fmt.Println("Connection closed, shutting down ")
break
}
line, err := reader.ReadBytes('\n')
if err != nil {
if sc.isStale() {
fmt.Println("conn stale, continue")
continue
}
time.Sleep(time.Second * time.Duration(sc.wait))
//try reconnecting, but exponentially back off until MaxWait is reached then exit?
resp, err := Connect(client, path, query)
if err != nil || resp == nil {
fmt.Println(" Could not reconnect to source? sleeping and will retry ")
if sc.wait < sc.maxWait {
sc.wait = sc.wait * 2
} else {
fmt.Println("exiting, max wait reached")
done <- true
return
}
continue
}
if resp.StatusCode != 200 {
fmt.Printf("resp.StatusCode = %d", resp.StatusCode)
if sc.wait < sc.maxWait {
sc.wait = sc.wait * 2
}
continue
}
reader = bufio.NewReader(resp.Body)
continue
} else if sc.wait != 1 {
sc.wait = 1
}
line = bytes.TrimSpace(line)
if len(line) == 0 {
continue
}
handler(line)
}
}
func Connect(client *twittergo.Client, path string, query url.Values) (resp *twittergo.APIResponse, err error) {
var (
req *http.Request
)
url := fmt.Sprintf("https://stream.twitter.com%v?%v", path, query.Encode())
req, err = http.NewRequest("GET", url, nil)
if err != nil {
err = fmt.Errorf("Could not parse request: %v\n", err)
return
}
resp, err = client.SendRequest(req)
if err != nil {
err = fmt.Errorf("Could not send request: %v\n", err)
return
}
return
}
func filterStream(client *twittergo.Client, path string, query url.Values) (err error) {
var (
resp *twittergo.APIResponse
)
sc := NewStreamConn(300)
resp, err = Connect(client, path, query)
done := make(chan bool)
stream := make(chan []byte, 1000)
go func() {
for data := range stream {
tweet := &twittergo.Tweet{}
err := json.Unmarshal(data, tweet)
if err == nil {
fmt.Printf("ID: %v\n", tweet.Id())
fmt.Printf("User: %v\n", tweet.User().ScreenName())
fmt.Printf("Tweet: %v\n", tweet.Text())
}
}
}()
readStream(client, sc, path, query, resp, func(line []byte) {
stream <- line
}, done)
return
}
func main() {
var (
err error
args *Args
client *twittergo.Client
)
args = parseArgs()
if client, err = LoadCredentials(); err != nil {
fmt.Printf("Could not parse CREDENTIALS file: %v\n", err)
os.Exit(1)
}
fmt.Println(args.Track)
query := url.Values{}
query.Set("track", args.Track)
fmt.Println("Printing everything about data science:")
fmt.Printf("=========================================================\n")
if err = filterStream(client, "/1.1/statuses/filter.json", query); err != nil {
fmt.Println("Error: %v\n", err)
}
fmt.Printf("\n\n")
}