aboutsummaryrefslogtreecommitdiff
path: root/web/mastodon/client.go
blob: bdcd8ec510bd74c5ad822c63a84a31f11341c00a (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
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
package mastodon

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"

	"within.website/x/web"
	"within.website/x/web/useragent"
)

// Client is the client for Mastodon
type Client struct {
	cli    *http.Client
	server *url.URL
	token  string
}

// Unauthenticated makes a new unauthenticated Mastodon client.
func Unauthenticated(botName, botURL, instanceURL string) (*Client, error) {
	u, err := url.Parse(instanceURL)
	if err != nil {
		return nil, err
	}

	return &Client{
		cli:    &http.Client{Transport: useragent.Transport(botName, botURL, http.DefaultTransport)},
		server: u,
	}, nil
}

// Authenticated makes a new authenticated Mastodon client.
func Authenticated(botName, botURL, instanceURL, token string) (*Client, error) {
	u, err := url.Parse(instanceURL)
	if err != nil {
		return nil, err
	}

	return &Client{
		cli: &http.Client{
			Transport: useragent.Transport(botName, botURL, authTransport{token, http.DefaultTransport}),
		},
		server: u,
		token:  token,
	}, nil
}

type authTransport struct {
	bearerToken string
	next        http.RoundTripper
}

var (
	_ http.RoundTripper = &authTransport{}
)

func (at authTransport) RoundTrip(r *http.Request) (*http.Response, error) {
	r.Header.Set("Authorization", fmt.Sprintf("Bearer %s", at.bearerToken))

	return at.next.RoundTrip(r)
}

func (c *Client) doJSONPost(ctx context.Context, path string, wantCode int, data any) (*http.Response, error) {
	h := http.Header{}
	h.Set("Content-Type", "application/json")
	h.Set("Accept", "application/json")

	var buf bytes.Buffer
	if err := json.NewEncoder(&buf).Encode(data); err != nil {
		return nil, err
	}

	return c.doRequest(ctx, http.MethodPost, "/api/v1/apps", h, http.StatusOK, &buf)
}

func (c *Client) doRequest(ctx context.Context, method, path string, headers http.Header, wantCode int, body io.Reader) (*http.Response, error) {
	u, err := c.server.Parse(path)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest(method, u.String(), body)
	if err != nil {
		return nil, fmt.Errorf("mastodon: can't make request: %w", err)
	}

	for key, hn := range headers {
		for _, hv := range hn {
			req.Header.Set(key, hv)
		}
	}

	resp, err := c.cli.Do(req)
	if err != nil {
		return nil, fmt.Errorf("mastodon: HTTP response error: %w", err)
	}

	if resp.StatusCode != wantCode {
		return nil, web.NewError(wantCode, resp)
	}

	return resp, nil
}