-
Notifications
You must be signed in to change notification settings - Fork 4
/
reddit.go
243 lines (204 loc) · 6.04 KB
/
reddit.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
package redditbot
import (
"context"
"fmt"
"net/http"
"strconv"
"sync"
"time"
"github.com/disgoorg/json"
"github.com/disgoorg/log"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/oauth2"
)
func NewReddit(cfg RedditConfig) (*Reddit, error) {
reddit := &Reddit{
config: &oauth2.Config{
ClientID: cfg.ClientID,
ClientSecret: cfg.ClientSecret,
Endpoint: oauth2.Endpoint{
TokenURL: "https://www.reddit.com/api/v1/access_token",
AuthStyle: oauth2.AuthStyleInHeader,
},
},
client: &http.Client{
Timeout: time.Second * 10,
},
}
if _, err := reddit.getToken(); err != nil {
return nil, err
}
return reddit, nil
}
type rateLimit struct {
used int
remaining int
reset time.Time
}
type Reddit struct {
config *oauth2.Config
client *http.Client
rateLimit rateLimit
token *oauth2.Token
mu sync.Mutex
}
func (r *Reddit) getToken() (*oauth2.Token, error) {
if r.token.Valid() {
return r.token, nil
}
token, err := r.config.Exchange(context.Background(), "", oauth2.SetAuthURLParam("grant_type", "client_credentials"))
if err != nil {
return nil, fmt.Errorf("error exchanging token: %w", err)
}
r.token = token
return token, nil
}
func (r *Reddit) do(rq *http.Request, important bool) (*http.Response, error) {
r.mu.Lock()
defer r.mu.Unlock()
log.Debugf("rate limit: used: %d, remaining: %d, reset: %s\n", r.rateLimit.used, r.rateLimit.remaining, r.rateLimit.reset.Format(time.RFC3339))
now := time.Now()
limit := 10
if important {
limit = 1
}
var sleep time.Duration
if r.rateLimit.remaining <= limit && now.Before(r.rateLimit.reset) {
sleep = r.rateLimit.reset.Sub(now)
time.Sleep(sleep)
}
token, err := r.getToken()
if err != nil {
return nil, err
}
rq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token.AccessToken))
rq.Header.Set("User-Agent", "discord:com.github.topi314.reddit-discord-bot:1.0.0 (by /u/TobiDragneel)")
rs, err := r.client.Do(rq)
if err != nil {
return nil, fmt.Errorf("error doing request: %w", err)
}
headers := rs.Header
used, err := strconv.ParseFloat(headers.Get("X-Ratelimit-Used"), 64)
if err != nil {
log.Error("error parsing x-ratelimit-used:", err.Error())
used = float64(r.rateLimit.used + 1)
}
remaining, err := strconv.ParseFloat(headers.Get("X-Ratelimit-Remaining"), 64)
if err != nil {
log.Error("error parsing x-ratelimit-remaining:", err.Error())
remaining = float64(r.rateLimit.remaining - 1)
}
reset, err := strconv.ParseFloat(headers.Get("X-Ratelimit-Reset"), 64)
if err != nil {
log.Error("error parsing x-ratelimit-reset:", err.Error())
reset = float64(r.rateLimit.reset.Unix())
}
r.rateLimit = rateLimit{
used: int(used),
remaining: int(remaining),
reset: now.Add(time.Second * time.Duration(reset)),
}
redditRequests.With(prometheus.Labels{
"path": rq.URL.Path,
"method": rq.Method,
"status": strconv.Itoa(rs.StatusCode),
"important": strconv.FormatBool(important),
"sleep": strconv.FormatInt(int64(sleep), 10),
"used": strconv.Itoa(r.rateLimit.used),
"remaining": strconv.Itoa(r.rateLimit.remaining),
"reset": strconv.FormatInt(r.rateLimit.reset.Unix(), 10),
}).Inc()
return rs, nil
}
func (r *Reddit) GetPosts(subreddit string, fetchType string, lastPost string) ([]RedditPost, string, error) {
url := fmt.Sprintf("https://oauth.reddit.com/r/%s/%s.json?raw_json=1&limit=100", subreddit, fetchType)
if lastPost != "" {
url += fmt.Sprintf("&before=%s", lastPost)
}
log.Debug("getting posts for url: ", url)
rq, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, "", err
}
rs, err := r.do(rq, false)
if err != nil {
return nil, "", err
}
defer rs.Body.Close()
if rs.StatusCode == http.StatusNotFound {
return nil, "", ErrSubredditNotFound
} else if rs.StatusCode == http.StatusForbidden {
return nil, "", ErrSubredditForbidden
}
var response RedditResponse[RedditListing[RedditPost]]
if err = json.NewDecoder(rs.Body).Decode(&response); err != nil {
return nil, "", err
}
before := response.Data.Before
posts := make([]RedditPost, 0, len(response.Data.Children))
for i := range response.Data.Children {
posts = append(posts, response.Data.Children[i].Data)
}
if response.Data.Before != "" {
var morePosts []RedditPost
morePosts, before, err = r.GetPosts(subreddit, fetchType, before)
if err != nil {
return nil, "", err
}
posts = append(posts, morePosts...)
}
if len(posts) > 0 && before == "" {
before = posts[0].Name
}
return posts, before, nil
}
func (r *Reddit) GetSubredditIcon(subreddit string) (string, error) {
url := fmt.Sprintf("https://oauth.reddit.com/r/%s/about.json?raw_json=1", subreddit)
rq, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
}
rs, err := r.do(rq, true)
if err != nil {
return "", err
}
defer rs.Body.Close()
if rs.StatusCode == http.StatusNotFound {
return "", ErrSubredditNotFound
} else if rs.StatusCode == http.StatusForbidden {
return "", ErrSubredditForbidden
}
var response RedditResponse[RedditAbout]
if err = json.NewDecoder(rs.Body).Decode(&response); err != nil {
return "", err
}
if response.Kind != "t5" {
return "", ErrSubredditNotFound
}
return response.Data.CommunityIcon, nil
}
type RedditResponse[T any] struct {
Kind string `json:"kind"`
Data T `json:"data"`
}
type RedditAbout struct {
CommunityIcon string `json:"community_icon"`
}
type RedditListing[T any] struct {
Before string `json:"before"`
Children []struct {
Data T `json:"data"`
} `json:"children"`
}
type RedditPost struct {
Selftext string `json:"selftext"`
AuthorFullname string `json:"author_fullname"`
Title string `json:"title"`
SubredditNamePrefixed string `json:"subreddit_name_prefixed"`
ID string `json:"id"`
Name string `json:"name"`
Author string `json:"author"`
URL string `json:"url"`
Permalink string `json:"permalink"`
CreatedUtc float64 `json:"created_utc"`
}