Get/create subreddit rules, get subreddit traffic

Signed-off-by: Vartan Benohanian <vartanbeno@gmail.com>
This commit is contained in:
Vartan Benohanian
2020-09-13 18:43:03 -04:00
parent 8a9e41181d
commit 9c85166c66
4 changed files with 475 additions and 0 deletions
+162
View File
@@ -2,11 +2,14 @@ package reddit
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/google/go-querystring/query"
)
// SubredditService handles communication with the subreddit
@@ -43,6 +46,100 @@ type Ban struct {
Note string `json:"note,omitempty"`
}
// SubredditRule is a rule in the subreddit.
type SubredditRule struct {
// One of: comment, link (i.e. post), or all (i.e. both comment and link).
Kind string `json:"kind,omitempty"`
// Short description of the rule.
Name string `json:"short_name,omitempty"`
// The reason that will appear when a thing is reported in violation to this rule.
ViolationReason string `json:"violation_reason,omitempty"`
Description string `json:"description,omitempty"`
Priority int `json:"priority"`
Created *Timestamp `json:"created_utc,omitempty"`
}
// SubredditRuleCreateRequest represents a request to add a subreddit rule.
type SubredditRuleCreateRequest struct {
// One of: comment, link (i.e. post) or all (i.e. both).
Kind string `url:"kind"`
// Short description of the rule. No longer than 100 characters.
Name string `url:"short_name"`
// The reason that will appear when a thing is reported in violation to this rule.
// If this is empty, Reddit will set its value to Name by default.
// No longer than 100 characters.
ViolationReason string `url:"violation_reason,omitempty"`
// Optional. No longer than 500 characters.
Description string `url:"description,omitempty"`
}
func (r *SubredditRuleCreateRequest) validate() error {
if r == nil {
return errors.New("*SubredditRuleCreateRequest: cannot be nil")
}
switch r.Kind {
case "comment", "link", "all":
// intentionally left blank
default:
return errors.New("(*SubredditRuleCreateRequest).Kind: must be one of: comment, link, all")
}
if r.Name == "" || len(r.Name) > 100 {
return errors.New("(*SubredditRuleCreateRequest).Name: must be between 1-100 characters")
}
if len(r.ViolationReason) > 100 {
return errors.New("(*SubredditRuleCreateRequest).ViolationReason: cannot be longer than 100 characters")
}
if len(r.Description) > 500 {
return errors.New("(*SubredditRuleCreateRequest).Description: cannot be longer than 500 characters")
}
return nil
}
// SubredditTrafficStats hold information about subreddit traffic.
type SubredditTrafficStats struct {
// Traffic data is returned in the form of day, hour, and month.
// Start is a timestamp indicating the start of the category, i.e.
// start of the day for day, start of the hour for hour, and start of the month for month.
Start *Timestamp `json:"start"`
UniqueViews int `json:"unique_views"`
TotalViews int `json:"total_views"`
// This is only available for "day" traffic, not hour and month.
// Therefore, it is always 0 by default for hour and month.
Subscribers int `json:"subscribers"`
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (s *SubredditTrafficStats) UnmarshalJSON(b []byte) error {
var data [4]int
err := json.Unmarshal(b, &data)
if err != nil {
return err
}
timestampByteValue, err := json.Marshal(data[0])
if err != nil {
return err
}
timestamp := new(Timestamp)
err = timestamp.UnmarshalJSON(timestampByteValue)
if err != nil {
return err
}
s.Start = timestamp
s.UniqueViews = data[1]
s.TotalViews = data[2]
s.Subscribers = data[3]
return nil
}
// todo: interface{}, seriously?
func (s *SubredditService) getPosts(ctx context.Context, sort string, subreddit string, opts interface{}) ([]*Post, *Response, error) {
path := sort
@@ -654,3 +751,68 @@ func (s *SubredditService) Moderators(ctx context.Context, subreddit string) ([]
return root.Data.Moderators, resp, nil
}
// Rules gets the rules of the subreddit.
func (s *SubredditService) Rules(ctx context.Context, subreddit string) ([]*SubredditRule, *Response, error) {
path := fmt.Sprintf("r/%s/about/rules", subreddit)
req, err := s.client.NewRequest(http.MethodGet, path, nil)
if err != nil {
return nil, nil, err
}
root := new(struct {
Rules []*SubredditRule `json:"rules"`
})
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return nil, resp, err
}
return root.Rules, resp, nil
}
// CreateRule adds a rule to the subreddit.
func (s *SubredditService) CreateRule(ctx context.Context, subreddit string, request *SubredditRuleCreateRequest) (*Response, error) {
err := request.validate()
if err != nil {
return nil, err
}
form, err := query.Values(request)
if err != nil {
return nil, err
}
form.Set("api_type", "json")
path := fmt.Sprintf("r/%s/api/add_subreddit_rule", subreddit)
req, err := s.client.NewRequest(http.MethodPost, path, form)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// Traffic gets the traffic data of the subreddit.
// It returns traffic data by day, hour, and month, respectively.
func (s *SubredditService) Traffic(ctx context.Context, subreddit string) ([]*SubredditTrafficStats, []*SubredditTrafficStats, []*SubredditTrafficStats, *Response, error) {
path := fmt.Sprintf("r/%s/about/traffic", subreddit)
req, err := s.client.NewRequest(http.MethodGet, path, nil)
if err != nil {
return nil, nil, nil, nil, err
}
root := new(struct {
Day []*SubredditTrafficStats `json:"day"`
Hour []*SubredditTrafficStats `json:"hour"`
Month []*SubredditTrafficStats `json:"month"`
})
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return nil, nil, nil, resp, err
}
return root.Day, root.Hour, root.Month, resp, nil
}
+134
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"net/http"
"net/url"
"strings"
"testing"
"time"
@@ -274,6 +275,47 @@ var expectedModerators = []*Moderator{
},
}
var expectedRules = []*SubredditRule{
{
Kind: "link",
Name: "Read the Rules Before Posting",
ViolationReason: "Read the Rules Before Posting",
Description: "https://www.reddit.com/r/Fitness/wiki/rules",
Priority: 0,
Created: &Timestamp{time.Date(2019, 5, 22, 5, 32, 58, 0, time.UTC)},
},
{
Kind: "link",
Name: "Read the Wiki Before Posting",
ViolationReason: "Read the Wiki Before Posting",
Description: "https://thefitness.wiki",
Priority: 1,
Created: &Timestamp{time.Date(2019, 11, 9, 7, 56, 33, 0, time.UTC)},
},
}
var expectedDayTraffic = []*SubredditTrafficStats{
{&Timestamp{time.Date(2020, 9, 13, 0, 0, 0, 0, time.UTC)}, 0, 0, 0},
{&Timestamp{time.Date(2020, 9, 12, 0, 0, 0, 0, time.UTC)}, 1, 12, 0},
{&Timestamp{time.Date(2020, 9, 11, 0, 0, 0, 0, time.UTC)}, 5, 85, 0},
{&Timestamp{time.Date(2020, 9, 10, 0, 0, 0, 0, time.UTC)}, 4, 20, 0},
{&Timestamp{time.Date(2020, 9, 9, 0, 0, 0, 0, time.UTC)}, 2, 64, 0},
{&Timestamp{time.Date(2020, 9, 8, 0, 0, 0, 0, time.UTC)}, 2, 95, 0},
{&Timestamp{time.Date(2020, 9, 7, 0, 0, 0, 0, time.UTC)}, 3, 41, 0},
}
var expectedHourTraffic = []*SubredditTrafficStats{
{&Timestamp{time.Date(2020, 9, 12, 20, 0, 0, 0, time.UTC)}, 1, 12, 0},
{&Timestamp{time.Date(2020, 9, 11, 3, 0, 0, 0, time.UTC)}, 4, 57, 0},
{&Timestamp{time.Date(2020, 9, 11, 2, 0, 0, 0, time.UTC)}, 4, 28, 0},
}
var expectedMonthTraffic = []*SubredditTrafficStats{
{&Timestamp{time.Date(2020, 9, 1, 0, 0, 0, 0, time.UTC)}, 7, 481, 0},
{&Timestamp{time.Date(2020, 8, 1, 0, 0, 0, 0, time.UTC)}, 5, 346, 0},
{&Timestamp{time.Date(2020, 7, 1, 0, 0, 0, 0, time.UTC)}, 4, 264, 0},
}
func TestSubredditService_HotPosts(t *testing.T) {
client, mux, teardown := setup()
defer teardown()
@@ -1021,3 +1063,95 @@ func TestSubredditService_Moderators(t *testing.T) {
require.NoError(t, err)
require.Equal(t, expectedModerators, moderators)
}
func TestSubredditService_Rules(t *testing.T) {
client, mux, teardown := setup()
defer teardown()
blob, err := readFileContents("../testdata/subreddit/rules.json")
require.NoError(t, err)
mux.HandleFunc("/r/testsubreddit/about/rules", func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, http.MethodGet, r.Method)
fmt.Fprint(w, blob)
})
rules, _, err := client.Subreddit.Rules(ctx, "testsubreddit")
require.NoError(t, err)
require.Equal(t, expectedRules, rules)
}
func TestSubredditService_CreateRule(t *testing.T) {
client, mux, teardown := setup()
defer teardown()
mux.HandleFunc("/r/testsubreddit/api/add_subreddit_rule", func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, http.MethodPost, r.Method)
form := url.Values{}
form.Set("api_type", "json")
form.Set("kind", "all")
form.Set("short_name", "testname")
form.Set("violation_reason", "testreason")
form.Set("description", "testdescription")
err := r.ParseForm()
require.NoError(t, err)
require.Equal(t, form, r.PostForm)
})
_, err := client.Subreddit.CreateRule(ctx, "testsubreddit", &SubredditRuleCreateRequest{
Kind: "all",
Name: "testname",
ViolationReason: "testreason",
Description: "testdescription",
})
require.NoError(t, err)
}
func TestSubredditService_CreateRule_Error(t *testing.T) {
client, _, teardown := setup()
defer teardown()
_, err := client.Subreddit.CreateRule(ctx, "testsubreddit", nil)
require.EqualError(t, err, "*SubredditRuleCreateRequest: cannot be nil")
_, err = client.Subreddit.CreateRule(ctx, "testsubreddit", &SubredditRuleCreateRequest{Kind: "invalid"})
require.EqualError(t, err, "(*SubredditRuleCreateRequest).Kind: must be one of: comment, link, all")
_, err = client.Subreddit.CreateRule(ctx, "testsubreddit", &SubredditRuleCreateRequest{Kind: "all", Name: ""})
require.EqualError(t, err, "(*SubredditRuleCreateRequest).Name: must be between 1-100 characters")
_, err = client.Subreddit.CreateRule(ctx, "testsubreddit", &SubredditRuleCreateRequest{
Kind: "all",
Name: "testname",
ViolationReason: strings.Repeat("x", 101),
})
require.EqualError(t, err, "(*SubredditRuleCreateRequest).ViolationReason: cannot be longer than 100 characters")
_, err = client.Subreddit.CreateRule(ctx, "testsubreddit", &SubredditRuleCreateRequest{
Kind: "all",
Name: "testname",
Description: strings.Repeat("x", 501),
})
require.EqualError(t, err, "(*SubredditRuleCreateRequest).Description: cannot be longer than 500 characters")
}
func TestSubredditService_Traffic(t *testing.T) {
client, mux, teardown := setup()
defer teardown()
blob, err := readFileContents("../testdata/subreddit/traffic.json")
require.NoError(t, err)
mux.HandleFunc("/r/testsubreddit/about/traffic", func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, http.MethodGet, r.Method)
fmt.Fprint(w, blob)
})
dayTraffic, hourTraffic, monthTraffic, _, err := client.Subreddit.Traffic(ctx, "testsubreddit")
require.NoError(t, err)
require.Equal(t, expectedDayTraffic, dayTraffic)
require.Equal(t, expectedHourTraffic, hourTraffic)
require.Equal(t, expectedMonthTraffic, monthTraffic)
}