-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtwitter.go
228 lines (191 loc) · 6.5 KB
/
twitter.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
package twitter
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/mrjones/oauth"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
)
// Constants
const (
BaseURL = "https://api.twitter.com/2"
RequestTokenURL = "https://api.twitter.com/oauth/request_token"
AuthorizeTokenURL = "https://api.twitter.com/oauth/authorize"
AccessTokenURL = "https://api.twitter.com/oauth/access_token"
TokenURL = "https://api.twitter.com/oauth2/token"
RateLimitStatusURL = "https://api.twitter.com/1.1/application/rate_limit_status.json"
)
// Twitter API Client
type Twitter struct {
client *http.Client
baseURL string
queue *Queue
}
// NewTwitter returns a new Twitter API v2 Client using OAuth 2.0 based authentication.
// This method is usufull when you only need to make Application-Only requests.
// Official Documentation: https://developer.twitter.com/en/docs/authentication/oauth-2-0
func NewTwitter(consumerKey, consumerSecret string) (*Twitter, error) {
// create new context
ctx := context.Background()
// init new Twitter client
api := &Twitter{
baseURL: BaseURL,
}
// oauth2 configures a client that uses app credentials to keep a fresh token
config := &clientcredentials.Config{
ClientID: consumerKey,
ClientSecret: consumerSecret,
TokenURL: TokenURL,
}
// Use the custom HTTP client when requesting a token.
httpClient := &http.Client{Timeout: 30 * time.Second}
ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient)
// http.Client will automatically authorize Requests
api.client = config.Client(ctx)
return api, nil
}
// NewTwitter returns a new Twitter API v2 Client using OAuth 2.0 based authentication.
// This method is usufull when you only need to make Application-Only requests.
// Official Documentation: https://developer.twitter.com/en/docs/authentication/oauth-2-0
// Scopes: https://developer.twitter.com/en/docs/authentication/oauth-2-0/authorization-code
// func NewTwitterWithPKCE(consumerKey, consumerSecret, accessToken, accessTokenSecret string) (*Twitter, error) {
// // create new context
// ctx := context.Background()
// // init new Twitter client
// api := &Twitter{
// baseURL: BaseURL,
// }
// // oauth2 configures a client that uses app credentials to keep a fresh token
// config := &oauth2.Config{
// ClientID: consumerKey,
// ClientSecret: consumerSecret,
// Scopes: []string{
// "tweet.read",
// "users.read",
// "offline.access",
// },
// Endpoint: oauth2.Endpoint{
// AuthURL: AuthorizeTokenURL,
// TokenURL: TokenURL,
// },
// }
// // Redirect user to consent page to ask for permission
// // for the scopes specified above.
// url := config.AuthCodeURL("state", oauth2.AccessTypeOffline,
// oauth2.SetAuthURLParam("code_challenge", "challenge"),
// oauth2.SetAuthURLParam("code_challenge_method", "plain"),
// oauth2.SetAuthURLParam("response_type", "code"),
// )
// fmt.Printf("Visit the URL for the auth dialog: %v", url)
// // Use the authorization code that is pushed to the redirect
// // URL. Exchange will do the handshake to retrieve the
// // initial access token. The HTTP Client returned by
// // conf.Client will refresh the token as necessary.
// var code string
// if _, err := fmt.Scan(&code); err != nil {
// return nil, err
// }
// tok, err := config.Exchange(ctx, code)
// if err != nil {
// return nil, err
// }
// api.client = config.Client(ctx, tok)
// return api, nil
// }
// NewTwitterWithContext returns a new Twitter API v2 Client using OAuth 1.0 based authentication.
// This method is useful when you need to make API requests, on behalf of a Twitter account.
// Official Documentation: https://developer.twitter.com/en/docs/authentication/oauth-1-0a
func NewTwitterWithContext(consumerKey, consumerSecret, accessToken, accessTokenSecret string) (*Twitter, error) {
// init new Twitter client
api := &Twitter{
baseURL: BaseURL,
}
// create the consumer
oauthConsumer := oauth.NewConsumer(consumerKey, consumerSecret, oauth.ServiceProvider{
RequestTokenUrl: RequestTokenURL,
AuthorizeTokenUrl: AuthorizeTokenURL,
AccessTokenUrl: AccessTokenURL,
})
//set tokens
oauthToken := oauth.AccessToken{
Token: accessToken,
Secret: accessTokenSecret,
}
// Use the custom HTTP client with tokens
httpClient, err := oauthConsumer.MakeHttpClient(&oauthToken)
if err != nil {
return nil, err
}
// http.Client will automatically authorize Requests
api.client = httpClient
return api, nil
}
// GetClient Get HTTP Client
func (api *Twitter) GetClient() *http.Client {
return api.client
}
// VerifyCredentials returns bool upon successful request. This method will make a request
// on the rate-limit endpoint since there is no official token validation method.
func (api *Twitter) VerifyCredentials() (bool, error) {
response, err := api.client.Get(RateLimitStatusURL)
if err != nil {
return false, err
}
defer response.Body.Close()
return err == nil, nil
}
// parseResponse returns an error while unmarshaling response body to the results interface.
func (api *Twitter) parseResponse(resp *http.Response, results *Data) error {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, &results)
if err != nil {
return err
}
return nil
}
// parseResponseWithInterface
func (api *Twitter) parseResponseWithInterface(resp *http.Response) ([]byte, error) {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
// apiDo send's the request to Twitter API and returns an error.
// The results are processed by `parseResponse` and written to the temporary
// `req.Results` interaface.
func (api *Twitter) apiDo(req *Request) error {
resp, err := api.client.Do(req.Req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return errors.New(fmt.Sprintf("%d - %s", resp.StatusCode, resp.Status))
}
return api.parseResponse(resp, &req.Results)
}
// apiDoWithResponse send's the request to Twitter API and returns an error.
// The results are processed by `parseResponse` and written to the temporary
// `req.Results` interaface.
func (api *Twitter) apiDoWithResponse(req *Request) ([]byte, error) {
resp, err := api.client.Do(req.Req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, errors.New(fmt.Sprintf("%d - %s", resp.StatusCode, resp.Status))
}
return api.parseResponseWithInterface(resp)
}