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

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

	"within.website/x/web"
)

func (c *Client) UploadMedia(ctx context.Context, fin io.Reader, fname, description, focus string) (*Attachment, error) {
	var buf bytes.Buffer

	w := multipart.NewWriter(&buf)
	fout, err := w.CreateFormFile("file", fname)
	if err != nil {
		return nil, err
	}
	if _, err := io.Copy(fout, fin); err != nil {
		return nil, err
	}

	if err := w.Close(); err != nil {
		return nil, fmt.Errorf("can't prepare form: %w", err)
	}

	u, err := c.server.Parse("/api/v1/media")
	if err != nil {
		return nil, err
	}

	q := u.Query()

	if description != "" {
		q.Set("description", description)
	}
	if focus != "" {
		q.Set("focus", focus)
	}

	u.RawQuery = q.Encode()

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), &buf)
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", w.FormDataContentType())

	resp, err := c.cli.Do(req)
	if err != nil {
		return nil, fmt.Errorf("can't post to %s: %w", u, err)
	}

	defer resp.Body.Close()

	switch resp.StatusCode {
	case http.StatusOK, http.StatusCreated:
	// This is okay
	default:
		return nil, web.NewError(http.StatusOK, resp)
	}

	var result Attachment

	if err := json.NewDecoder(io.LimitReader(resp.Body, 1024*1024*2)).Decode(&result); err != nil {
		return nil, fmt.Errorf("can't decode JSON: %w", err)
	}

	return &result, nil
}