package equipo import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "mime" "net/http" "net/url" "regexp" "strings" "time" "unicode/utf8" ) // Attachment is one of a message's files, as Equipo's // wire.MessageAttachment has it, with only the fields Base passes on: no // URL of Equipo's ever reaches a client, which builds Base's own // (/ask/attachments/{id}). Kind is image or file; Width and Height are an // image's upright size, 0 for a file. type Attachment struct { ID string `json:"id"` Kind string `json:"kind"` Name string `json:"name"` MediaType string `json:"media_type"` Size int64 `json:"size"` Width int `json:"width"` Height int `json:"height"` } // ValidAttachmentID reports whether id has the shape of an Equipo // attachment id: Base calls Equipo with no other. func ValidAttachmentID(id string) bool { return attachmentID.MatchString(id) } var attachmentID = regexp.MustCompile(`^at_[a-z0-9]{8,60}$`) // Clean is the message as Base passes it on: its lookups within bounds // (cleanLookups), and only the attachments whose id it would call Equipo // with, each with a kind Base draws (an unknown kind // is a file), a name of valid UTF-8 (at most 255 bytes; "file" when // empty), and no negative size or side. Nil when none are left, so a // message without files is what it always was. func (m Message) Clean() Message { var out []Attachment for _, a := range m.Attachments { if !ValidAttachmentID(a.ID) { continue } if a.Kind != AttachmentImage { a.Kind = AttachmentFile } a.Name = strings.ToValidUTF8(a.Name, "") for len(a.Name) > 255 { _, n := utf8.DecodeLastRuneInString(a.Name) a.Name = a.Name[:len(a.Name)-n] } if strings.TrimSpace(a.Name) == "" { a.Name = "file" } a.Size, a.Width, a.Height = max(a.Size, 0), max(a.Width, 0), max(a.Height, 0) out = append(out, a) } m.Attachments = out m.Lookups = cleanLookups(m.Role, m.Lookups) return m } // CleanAttachment is one attachment as Clean passes it on (an id Base // would not call Equipo with comes back empty). func CleanAttachment(a Attachment) Attachment { m := Message{Attachments: []Attachment{a}}.Clean() if len(m.Attachments) == 0 { return Attachment{} } return m.Attachments[0] } // The kinds of attachment. const ( AttachmentImage = "image" AttachmentFile = "file" ) // MaxUpload is the most an upload may be: Equipo's attach.MaxBytes, // 10 MiB. MaxFiles is the most a message may carry. const ( MaxUpload = 10 << 20 MaxFiles = 5 ) var ( // ErrAttachmentsUnavailable: the person's runner can't take files // (never seen, or older than the protocol that carries them). Nothing // was stored; words alone still send. ErrAttachmentsUnavailable = &Error{Status: 409, Code: "attachments_unavailable"} // ErrNotFound: no such file for the person (another's, or gone). ErrNotFound = &Error{Status: 404} ) // fileTimeout is FileTimeout's default. const fileTimeout = 60 * time.Second // do sends one request with a raw body of size bytes (nil for none) and // returns the answer unread, for the caller to read and close. A non-2xx // answer is an *Error with Equipo's code, its body read (a little) and // closed. It gives up when the headers take longer than FileTimeout; the // body is bounded by ctx alone. func (c *Client) do(ctx context.Context, method, path, token string, header http.Header, body []byte) (*http.Response, error) { ctx, cancel := context.WithCancel(ctx) var in io.Reader if body != nil { in = bytes.NewReader(body) } req, err := http.NewRequestWithContext(ctx, method, c.origin+path, in) if err != nil { cancel() return nil, err } for k, v := range header { req.Header[k] = v } req.Header.Set("Authorization", "Bearer "+token) setCapabilities(ctx, req) late := time.AfterFunc(c.fileTimeout(), cancel) res, err := c.http.Do(req) if !late.Stop() && err == nil { res.Body.Close() err = context.DeadlineExceeded } if err != nil { cancel() return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { var e struct { Code string `json:"code"` } raw, _ := io.ReadAll(io.LimitReader(res.Body, 4<<10)) _ = json.Unmarshal(raw, &e) res.Body.Close() cancel() return nil, &Error{Status: res.StatusCode, Code: e.Code, RetryAfter: res.Header.Get("Retry-After")} } res.Body = cancelOnClose{res.Body, cancel} return res, nil } func (c *Client) fileTimeout() time.Duration { if c.FileTimeout > 0 { return c.FileTimeout } return fileTimeout } // Upload sends one file to POST /api/v1/attachments: the bytes as the // body (with their length, which Equipo wants), the declared type in // Content-Type and the name in Content-Disposition (RFC 2231's filename* // for a name beyond ASCII). It carries no Idempotency-Key: Equipo's upload // takes none, and a retry is a second upload. Equipo's refusals come back // as an *Error with their code: attachment_too_large (413), // attachment_type and attachment_heic (415), attachment_pixels (413), // attachment_limit (409). func (c *Client) Upload(ctx context.Context, token, name, mediaType string, body []byte) (Attachment, error) { if mediaType == "" { mediaType = "application/octet-stream" } disposition := mime.FormatMediaType("attachment", map[string]string{"filename": name}) if disposition == "" { disposition = "attachment" } h := http.Header{"Content-Type": {mediaType}, "Content-Disposition": {disposition}, "Accept": {"application/json"}} ctx, cancel := context.WithTimeout(ctx, c.fileTimeout()) defer cancel() res, err := c.do(ctx, http.MethodPost, "/api/v1/attachments", token, h, body) if err != nil { return Attachment{}, err } defer res.Body.Close() var out Attachment raw, err := io.ReadAll(io.LimitReader(res.Body, 64<<10)) if err == nil { err = json.Unmarshal(raw, &out) } if err != nil || out.ID == "" { return Attachment{}, fmt.Errorf("equipo: upload: %w", errors.Join(err, errors.New("no attachment in the answer"))) } return out, nil } // OpenAttachment reads one of the person's files (its preview, an image's // thumbnail, with preview): the answer unread, for the caller to stream // and close. It is bounded by ctx, and by FileTimeout for the headers. A // file that isn't the person's, or is gone, is ErrNotFound. func (c *Client) OpenAttachment(ctx context.Context, token, id string, preview bool) (*http.Response, error) { path := "/api/v1/attachments/" + url.PathEscape(id) if preview { path += "/preview" } return c.do(ctx, http.MethodGet, path, token, nil, nil) } // DeleteAttachment deletes one of the person's unsent uploads. Equipo's // 204, and its 404 (not the person's, or already gone), are done; a file // already sent is 409 attachment_sent. func (c *Client) DeleteAttachment(ctx context.Context, token, id string) error { _, err := c.call(ctx, http.MethodDelete, "/api/v1/attachments/"+url.PathEscape(id), token, "", nil, nil, nil) if errors.Is(err, ErrNotFound) { return nil } return err }