aboutsummaryrefslogtreecommitdiff
path: root/web/switchcounter/switchc.go
blob: 7acbe432538e8ebb5d094779fd956507508f49be (plain)
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
// Package switchcounter is a simple interface to the https://www.switchcounter.science/ API.
package switchcounter

import (
	"bytes"
	"encoding/json"
	"net/http"
	"time"

	"within.website/x/web"
)

type arg struct {
	Command    string `json:"command"` // always "switch"
	MemberName string `json:"member_name,omitempty"`
}

// Status is the API response.
type Status struct {
	Front     string    `json:"member_name"`
	StartedAt time.Time `json:"started_at"`
}

// Validate ensures a HTTP response contains the expected fields.
func Validate(resp *http.Response) error {
	if resp.StatusCode == http.StatusOK {
		return nil
	}

	return web.NewError(http.StatusOK, resp)
}

// API is a builder for HTTP requests to interface with Switch Counter.
type API struct {
	url string // webhook url
}

func (a API) makeRequestWith(body interface{}) (*http.Request, error) {
	env := struct {
		Webhook interface{} `json:"webhook"`
	}{
		Webhook: body,
	}
	data, err := json.Marshal(env)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest(http.MethodPost, a.url, bytes.NewBuffer(data))
	if err != nil {
		return nil, err
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	return req, nil
}

// Status returns a request for which systemmate is currently in front.
func (a API) Status() *http.Request {
	result, err := a.makeRequestWith(arg{Command: "switch"})
	if err != nil {
		panic(err)
	}
	return result
}

// Switch changes the recorded front to the given systemmate.
func (a API) Switch(front string) *http.Request {
	result, err := a.makeRequestWith(arg{Command: "switch", MemberName: front})
	if err != nil {
		panic(err)
	}
	return result
}

// NewHTTPClient creates a new instance of API over HTTP.
func NewHTTPClient(webhookURL string) API {
	return API{
		url: webhookURL,
	}
}