apollo-backend/internal/reddit/client.go

133 lines
2.3 KiB
Go
Raw Normal View History

2021-05-10 00:51:15 +00:00
package reddit
import (
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/valyala/fastjson"
2021-05-10 00:51:15 +00:00
)
const (
tokenURL = "https://www.reddit.com/api/v1/access_token"
)
type Client struct {
id string
secret string
client *http.Client
parser *fastjson.Parser
2021-05-10 00:51:15 +00:00
}
func NewClient(id, secret string) *Client {
tr := &http.Transport{
MaxIdleConnsPerHost: 128,
}
client := &http.Client{Transport: tr}
parser := &fastjson.Parser{}
return &Client{
id,
secret,
client,
parser,
}
2021-05-10 00:51:15 +00:00
}
type AuthenticatedClient struct {
*Client
refreshToken string
accessToken string
expiry *time.Time
}
func (rc *Client) NewAuthenticatedClient(refreshToken, accessToken string) *AuthenticatedClient {
return &AuthenticatedClient{rc, refreshToken, accessToken, nil}
}
func (rac *AuthenticatedClient) request(r *Request) ([]byte, error) {
req, err := r.HTTPRequest()
if err != nil {
return nil, err
}
resp, err := rac.client.Do(req)
2021-05-10 00:51:15 +00:00
if err != nil {
return nil, err
}
defer resp.Body.Close()
2021-05-10 00:51:15 +00:00
return ioutil.ReadAll(resp.Body)
}
2021-06-24 02:19:43 +00:00
func (rac *AuthenticatedClient) RefreshTokens() (*RefreshTokenResponse, error) {
2021-05-10 00:51:15 +00:00
req := NewRequest(
WithMethod("POST"),
WithURL(tokenURL),
WithBody("grant_type", "refresh_token"),
WithBody("refresh_token", rac.refreshToken),
WithBasicAuth(rac.id, rac.secret),
)
body, err := rac.request(req)
2021-06-24 02:19:43 +00:00
if err != nil {
return nil, err
}
rtr := &RefreshTokenResponse{}
json.Unmarshal([]byte(body), rtr)
return rtr, nil
2021-05-10 00:51:15 +00:00
}
2021-06-24 02:19:43 +00:00
func (rac *AuthenticatedClient) MessageInbox(from string) (*MessageListingResponse, error) {
2021-05-10 00:51:15 +00:00
req := NewRequest(
WithMethod("GET"),
WithToken(rac.accessToken),
WithURL("https://oauth.reddit.com/message/inbox.json"),
2021-06-24 02:19:43 +00:00
WithQuery("before", from),
2021-05-10 00:51:15 +00:00
)
2021-06-24 02:19:43 +00:00
body, err := rac.request(req)
if err != nil {
return nil, err
}
mlr := &MessageListingResponse{}
json.Unmarshal([]byte(body), mlr)
return mlr, nil
2021-05-10 00:51:15 +00:00
}
type MeResponse struct {
Name string
}
func (mr *MeResponse) NormalizedUsername() string {
return strings.ToLower(mr.Name)
}
func (rac *AuthenticatedClient) Me() (*MeResponse, error) {
req := NewRequest(
WithMethod("GET"),
WithToken(rac.accessToken),
WithURL("https://oauth.reddit.com/api/v1/me"),
)
body, err := rac.request(req)
if err != nil {
return nil, err
}
mr := &MeResponse{}
err = json.Unmarshal(body, mr)
return mr, err
}