/
main.go
230 lines (194 loc) · 4.34 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package main
import (
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"sync"
"time"
"github.com/ChimeraCoder/anaconda"
"github.com/garyburd/redigo/redis"
"github.com/jzelinskie/geddit"
)
const ua = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.130 Safari/537.36"
var (
session = geddit.NewSession(ua)
pool = newPool("/tmp/monks.sock")
)
func init() {
ck := os.Getenv("CONSUMERKEY")
cs := os.Getenv("CONSUMERSECRET")
if ck == "" || cs == "" {
panic("Cannot have empty API key/secret/token")
}
anaconda.SetConsumerKey(ck)
anaconda.SetConsumerSecret(cs)
}
func ParseRedistogoURL(u string) (string, string) {
redisUrl := u
redisInfo, _ := url.Parse(redisUrl)
server := redisInfo.Host
password := ""
if redisInfo.User != nil {
password, _ = redisInfo.User.Password()
}
return server, password
}
func newPool(socket string) *redis.Pool {
url, pass := ParseRedistogoURL(os.Getenv("REDISTOGO_URL"))
return &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial(url, pass)
if err != nil {
return nil, err
}
if _, err := c.Do("AUTH", pass); err != nil {
c.Close()
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
type tweets struct {
api *anaconda.TwitterApi
tweets []*tweet
}
type tweet struct {
title, img string
}
func CollectImages(api *anaconda.TwitterApi) {
subs, err := session.SubredditSubmissions("monkslookingatbeer", geddit.NewSubmissions, geddit.ListingOptions{})
if err != nil {
panic(err)
}
t := &tweets{api: api}
for _, v := range subs {
if !v.IsSelf {
if title, u := parse(v); u != nil && title != "" {
if img := getImage(u); img != "" {
if !havePosted(img) {
t.tweets = append(t.tweets, &tweet{title: title, img: img})
}
}
}
}
}
}
func havePosted(url string) bool {
conn := pool.Get()
defer conn.Close()
reply, err := conn.Do("GET", url)
if reply != nil && err == nil {
b, ok := reply.([]byte)
return ok && string(b) == url
}
return false
}
var reg = regexp.MustCompile("png|jpeg|jpg|gif")
func parse(sub *geddit.Submission) (string, *url.URL) {
u, err := url.Parse(sub.URL)
if err != nil {
panic(err)
}
if !reg.Match([]byte(filepath.Ext(u.Path))) {
if sub.Domain != "imgur.com" {
return "", nil
}
// imgur/ddfdsf.jpg == imgur/ddfdsf.png
u.Path = u.Path + ".jpg"
}
return sub.Title, u
}
func getImage(u *url.URL) string {
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
panic(err)
}
req.Header.Set("User-Agent", ua)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return ""
}
defer resp.Body.Close()
cont, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
return base64.StdEncoding.EncodeToString(cont)
}
func (t *tweets) Tweet(status string, media anaconda.Media) error {
v := url.Values{
"media_ids": []string{media.MediaIDString},
}
_, err := t.api.PostTweet(status, v)
if err != nil {
fmt.Printf("Status: %q\n", status)
}
return err
}
func checkErr(err error) {
if aerr, ok := err.(*anaconda.ApiError); ok {
if isRateLimitError, nextWindow := aerr.RateLimitCheck(); isRateLimitError {
<-time.After(nextWindow.Sub(time.Now()))
}
}
}
func addPost(title string) {
conn := pool.Get()
defer conn.Close()
_, err := conn.Do("SETEX", title, 2592000, "t")
if err != nil {
panic(err)
}
}
func (t *tweets) doTweets() {
for _, tweet := range t.tweets {
// If there are API errors just skip that post.
media, err := t.api.UploadMedia(tweet.img)
if err != nil {
checkErr(err)
continue
}
checkErr(t.Tweet(tweet.title, media))
addPost(tweet.title)
}
}
func main() {
at := os.Getenv("ACCESSTOKEN")
as := os.Getenv("ACCESSSECRET")
if at == "" || as == "" {
panic("Cannot have empty API key/secret/token")
}
api := anaconda.NewTwitterApi(at, as)
api.EnableThrottling(5*time.Minute, 100)
api.SetDelay(5 * time.Minute)
ticker := time.NewTicker(6 * time.Hour)
quit := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
for {
select {
case <-ticker.C:
fmt.Println("collecting images")
CollectImages(api)
case <-quit:
ticker.Stop()
return
}
}
}()
wg.Wait()
}