oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1package equipo
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "mime"
11 "net/http"
12 "net/url"
13 "regexp"
14 "strings"
15 "time"
16 "unicode/utf8"
17)
18
19// Attachment is one of a message's files, as Equipo's
20// wire.MessageAttachment has it, with only the fields Base passes on: no
21// URL of Equipo's ever reaches a client, which builds Base's own
22// (/ask/attachments/{id}). Kind is image or file; Width and Height are an
23// image's upright size, 0 for a file.
24type Attachment struct {
25 ID string `json:"id"`
26 Kind string `json:"kind"`
27 Name string `json:"name"`
28 MediaType string `json:"media_type"`
29 Size int64 `json:"size"`
30 Width int `json:"width"`
31 Height int `json:"height"`
32}
33
34// ValidAttachmentID reports whether id has the shape of an Equipo
35// attachment id: Base calls Equipo with no other.
36func ValidAttachmentID(id string) bool { return attachmentID.MatchString(id) }
37
38var attachmentID = regexp.MustCompile(`^at_[a-z0-9]{8,60}$`)
39
40// Clean is the message as Base passes it on: its lookups within bounds
41// (cleanLookups), and only the attachments whose id it would call Equipo
42// with, each with a kind Base draws (an unknown kind
43// is a file), a name of valid UTF-8 (at most 255 bytes; "file" when
44// empty), and no negative size or side. Nil when none are left, so a
45// message without files is what it always was.
46func (m Message) Clean() Message {
47 var out []Attachment
48 for _, a := range m.Attachments {
49 if !ValidAttachmentID(a.ID) {
50 continue
51 }
52 if a.Kind != AttachmentImage {
53 a.Kind = AttachmentFile
54 }
55 a.Name = strings.ToValidUTF8(a.Name, "")
56 for len(a.Name) > 255 {
57 _, n := utf8.DecodeLastRuneInString(a.Name)
58 a.Name = a.Name[:len(a.Name)-n]
59 }
60 if strings.TrimSpace(a.Name) == "" {
61 a.Name = "file"
62 }
63 a.Size, a.Width, a.Height = max(a.Size, 0), max(a.Width, 0), max(a.Height, 0)
64 out = append(out, a)
65 }
66 m.Attachments = out
67 m.Lookups = cleanLookups(m.Role, m.Lookups)
68 return m
69}
70
71// CleanAttachment is one attachment as Clean passes it on (an id Base
72// would not call Equipo with comes back empty).
73func CleanAttachment(a Attachment) Attachment {
74 m := Message{Attachments: []Attachment{a}}.Clean()
75 if len(m.Attachments) == 0 {
76 return Attachment{}
77 }
78 return m.Attachments[0]
79}
80
81// The kinds of attachment.
82const (
83 AttachmentImage = "image"
84 AttachmentFile = "file"
85)
86
87// MaxUpload is the most an upload may be: Equipo's attach.MaxBytes,
88// 10 MiB. MaxFiles is the most a message may carry.
89const (
90 MaxUpload = 10 << 20
91 MaxFiles = 5
92)
93
94var (
95 // ErrAttachmentsUnavailable: the person's runner can't take files
96 // (never seen, or older than the protocol that carries them). Nothing
97 // was stored; words alone still send.
98 ErrAttachmentsUnavailable = &Error{Status: 409, Code: "attachments_unavailable"}
99 // ErrNotFound: no such file for the person (another's, or gone).
100 ErrNotFound = &Error{Status: 404}
101)
102
103// fileTimeout is FileTimeout's default.
104const fileTimeout = 60 * time.Second
105
106// do sends one request with a raw body of size bytes (nil for none) and
107// returns the answer unread, for the caller to read and close. A non-2xx
108// answer is an *Error with Equipo's code, its body read (a little) and
109// closed. It gives up when the headers take longer than FileTimeout; the
110// body is bounded by ctx alone.
111func (c *Client) do(ctx context.Context, method, path, token string, header http.Header, body []byte) (*http.Response, error) {
112 ctx, cancel := context.WithCancel(ctx)
113 var in io.Reader
114 if body != nil {
115 in = bytes.NewReader(body)
116 }
117 req, err := http.NewRequestWithContext(ctx, method, c.origin+path, in)
118 if err != nil {
119 cancel()
120 return nil, err
121 }
122 for k, v := range header {
123 req.Header[k] = v
124 }
125 req.Header.Set("Authorization", "Bearer "+token)
126 setCapabilities(ctx, req)
127 late := time.AfterFunc(c.fileTimeout(), cancel)
128 res, err := c.http.Do(req)
129 if !late.Stop() && err == nil {
130 res.Body.Close()
131 err = context.DeadlineExceeded
132 }
133 if err != nil {
134 cancel()
135 return nil, err
136 }
137 if res.StatusCode < 200 || res.StatusCode > 299 {
138 var e struct {
139 Code string `json:"code"`
140 }
141 raw, _ := io.ReadAll(io.LimitReader(res.Body, 4<<10))
142 _ = json.Unmarshal(raw, &e)
143 res.Body.Close()
144 cancel()
145 return nil, &Error{Status: res.StatusCode, Code: e.Code, RetryAfter: res.Header.Get("Retry-After")}
146 }
147 res.Body = cancelOnClose{res.Body, cancel}
148 return res, nil
149}
150
151func (c *Client) fileTimeout() time.Duration {
152 if c.FileTimeout > 0 {
153 return c.FileTimeout
154 }
155 return fileTimeout
156}
157
158// Upload sends one file to POST /api/v1/attachments: the bytes as the
159// body (with their length, which Equipo wants), the declared type in
160// Content-Type and the name in Content-Disposition (RFC 2231's filename*
161// for a name beyond ASCII). It carries no Idempotency-Key: Equipo's upload
162// takes none, and a retry is a second upload. Equipo's refusals come back
163// as an *Error with their code: attachment_too_large (413),
164// attachment_type and attachment_heic (415), attachment_pixels (413),
165// attachment_limit (409).
166func (c *Client) Upload(ctx context.Context, token, name, mediaType string, body []byte) (Attachment, error) {
167 if mediaType == "" {
168 mediaType = "application/octet-stream"
169 }
170 disposition := mime.FormatMediaType("attachment", map[string]string{"filename": name})
171 if disposition == "" {
172 disposition = "attachment"
173 }
174 h := http.Header{"Content-Type": {mediaType}, "Content-Disposition": {disposition}, "Accept": {"application/json"}}
175 ctx, cancel := context.WithTimeout(ctx, c.fileTimeout())
176 defer cancel()
177 res, err := c.do(ctx, http.MethodPost, "/api/v1/attachments", token, h, body)
178 if err != nil {
179 return Attachment{}, err
180 }
181 defer res.Body.Close()
182 var out Attachment
183 raw, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
184 if err == nil {
185 err = json.Unmarshal(raw, &out)
186 }
187 if err != nil || out.ID == "" {
188 return Attachment{}, fmt.Errorf("equipo: upload: %w", errors.Join(err, errors.New("no attachment in the answer")))
189 }
190 return out, nil
191}
192
193// OpenAttachment reads one of the person's files (its preview, an image's
194// thumbnail, with preview): the answer unread, for the caller to stream
195// and close. It is bounded by ctx, and by FileTimeout for the headers. A
196// file that isn't the person's, or is gone, is ErrNotFound.
197func (c *Client) OpenAttachment(ctx context.Context, token, id string, preview bool) (*http.Response, error) {
198 path := "/api/v1/attachments/" + url.PathEscape(id)
199 if preview {
200 path += "/preview"
201 }
202 return c.do(ctx, http.MethodGet, path, token, nil, nil)
203}
204
205// DeleteAttachment deletes one of the person's unsent uploads. Equipo's
206// 204, and its 404 (not the person's, or already gone), are done; a file
207// already sent is 409 attachment_sent.
208func (c *Client) DeleteAttachment(ctx context.Context, token, id string) error {
209 _, err := c.call(ctx, http.MethodDelete, "/api/v1/attachments/"+url.PathEscape(id), token, "", nil, nil, nil)
210 if errors.Is(err, ErrNotFound) {
211 return nil
212 }
213 return err
214}
215