| 1 | // agent_assets.go is how an agent puts a picture in a deck, over the |
| 2 | // bearer API: |
| 3 | // |
| 4 | // POST /api/v1/decks/{sqid}/assets?alt=<description> |
| 5 | // |
| 6 | // The body is the image itself, not JSON and not a signed upload: an |
| 7 | // agent has no browser to PUT to a bucket, and the registration endpoint |
| 8 | // in assets.go only verifies bytes a session staged. So this route does |
| 9 | // that endpoint's work on bytes it read itself. It judges them by what |
| 10 | // they are rather than by any header (a PNG, JPEG or WebP that decodes, |
| 11 | // within the size a picture may be), stores them under their own hash, |
| 12 | // writes the DeckAsset row that serveAsset requires, and applies |
| 13 | // `register_asset` through the ops path as the agent, so live editors |
| 14 | // see it and it has a seq, an actor and an undo step like any other |
| 15 | // change. |
| 16 | // |
| 17 | // SVG is refused here, though the browser path takes it through |
| 18 | // svg.go's sanitiser: a sanitised SVG has no pixel size to answer with, |
| 19 | // and an agent that has an SVG can as well send the picture of it. |
| 20 | // |
| 21 | // The same bytes twice for one deck are one asset: the second upload |
| 22 | // finds the ref already in the deck's map and answers it with 200, |
| 23 | // writing nothing to the document. |
| 24 | package slides |
| 25 | |
| 26 | import ( |
| 27 | "bytes" |
| 28 | "encoding/json" |
| 29 | "errors" |
| 30 | "image" |
| 31 | "io" |
| 32 | "net/http" |
| 33 | "slices" |
| 34 | "time" |
| 35 | |
| 36 | "gorm.io/gorm" |
| 37 | "gorm.io/gorm/clause" |
| 38 | |
| 39 | "amadan.net/oficina/slides/internal/slides/deck" |
| 40 | ) |
| 41 | |
| 42 | // apiAssetMessages is the developer's sentence for each refusal this |
| 43 | // route adds to the API's own. |
| 44 | var apiAssetMessages = map[string]string{ |
| 45 | errTooLarge: "A picture may be at most 20 MiB.", |
| 46 | "not_an_image": "A picture is a PNG, JPEG or WebP whose header reads, at most 30000 pixels either way and 50 megapixels in all. SVG is not taken here.", |
| 47 | "no_store": "This instance has no object store to keep pictures in.", |
| 48 | } |
| 49 | |
| 50 | // apiAssetFail answers one refusal with its code and its sentence. |
| 51 | func (a *app) apiAssetFail(w http.ResponseWriter, status int, code string) { |
| 52 | a.writeJSON(w, status, map[string]string{"error": code, "message": apiAssetMessages[code]}) |
| 53 | } |
| 54 | |
| 55 | // errAssetKnown is a batch not built because the deck already registers |
| 56 | // the ref: the upload is a duplicate, and there is nothing to write. |
| 57 | var errAssetKnown = errors.New("slides: the deck already registers this picture") |
| 58 | |
| 59 | // apiPostAsset serves POST /api/v1/decks/{sqid}/assets. |
| 60 | func (a *app) apiPostAsset(w http.ResponseWriter, r *http.Request) { |
| 61 | p, ok := a.apiPrincipal(w, r) |
| 62 | if !ok { |
| 63 | return |
| 64 | } |
| 65 | d, ok := a.apiDeckFor(w, r, p) |
| 66 | if !ok { |
| 67 | return |
| 68 | } |
| 69 | store := a.cfg.Blobs |
| 70 | if store == nil { |
| 71 | a.apiAssetFail(w, http.StatusServiceUnavailable, "no_store") |
| 72 | return |
| 73 | } |
| 74 | |
| 75 | raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxAssetBytes)) |
| 76 | if err != nil { |
| 77 | var tooBig *http.MaxBytesError |
| 78 | if errors.As(err, &tooBig) { |
| 79 | a.apiAssetFail(w, http.StatusRequestEntityTooLarge, errTooLarge) |
| 80 | return |
| 81 | } |
| 82 | apiFail(w, http.StatusBadRequest, errInvalid) |
| 83 | return |
| 84 | } |
| 85 | // Judged by its bytes: one of the three raster types by its magic, |
| 86 | // then a header that reads as a size a picture may be: 30000 pixels |
| 87 | // either way and 50 megapixels together, the budget every decode of |
| 88 | // it (thumbnail, export) is held to. Only the header is read, not the |
| 89 | // whole image. The size is what the image says it is, which is the |
| 90 | // only size there is for an agent to be held to. |
| 91 | kind := sniffImage(raw) |
| 92 | if kind != "image/png" && kind != "image/jpeg" && kind != "image/webp" { |
| 93 | a.apiAssetFail(w, http.StatusUnprocessableEntity, "not_an_image") |
| 94 | return |
| 95 | } |
| 96 | cfg, _, err := image.DecodeConfig(bytes.NewReader(raw)) |
| 97 | if err != nil || cfg.Width < 1 || cfg.Height < 1 || cfg.Width > maxAssetDimension || cfg.Height > maxAssetDimension || |
| 98 | cfg.Width*cfg.Height > maxImagePixels { |
| 99 | a.apiAssetFail(w, http.StatusUnprocessableEntity, "not_an_image") |
| 100 | return |
| 101 | } |
| 102 | alt := trimTo(r.URL.Query().Get("alt"), maxAssetAlt) |
| 103 | |
| 104 | // Content-addressed, as registerAsset promotes a browser's upload: |
| 105 | // the ref is the SHA-256 of these bytes. |
| 106 | stored, err := store.Put(r.Context(), bytes.NewReader(raw), kind) |
| 107 | if err != nil { |
| 108 | a.logger.Error("slides: keep an agent's picture", "deck", d.Sqid, "err", err) |
| 109 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 110 | return |
| 111 | } |
| 112 | ref := stored.Hash |
| 113 | |
| 114 | // The verification row serveAsset requires, as registerAsset writes |
| 115 | // it. Before the op, so a picture the deck names is always one it |
| 116 | // can serve; a row whose op then fails serves nothing, since the |
| 117 | // deck's map does not name the ref. |
| 118 | g := a.deckGuard(r.Context(), p.operator, d) |
| 119 | if err := a.guarded(r.Context(), g, func(db *gorm.DB) error { |
| 120 | return db.Clauses(clause.OnConflict{DoNothing: true}). |
| 121 | Create(&DeckAsset{DeckID: d.ID, Ref: ref, CreatedAt: time.Now().UTC()}).Error |
| 122 | }); err != nil { |
| 123 | if guardRefusedJSON(w, err) { |
| 124 | return |
| 125 | } |
| 126 | a.logger.Error("slides: record an agent's verified picture", "deck", d.Sqid, "err", err) |
| 127 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 128 | return |
| 129 | } |
| 130 | |
| 131 | assetID, err := newID() |
| 132 | if err != nil { |
| 133 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 134 | return |
| 135 | } |
| 136 | // Built from the document the write lands on, so a duplicate is |
| 137 | // judged against the deck as it is at the write, not as it was when |
| 138 | // the request began. |
| 139 | existing := "" |
| 140 | build := func(view *deck.Deck) ([]map[string]json.RawMessage, error) { |
| 141 | ids := make([]string, 0, len(view.Assets)) |
| 142 | for id, asset := range view.Assets { |
| 143 | if asset.Ref == ref { |
| 144 | ids = append(ids, id) |
| 145 | } |
| 146 | } |
| 147 | if len(ids) > 0 { |
| 148 | slices.Sort(ids) |
| 149 | existing = ids[0] |
| 150 | return nil, errAssetKnown |
| 151 | } |
| 152 | return []map[string]json.RawMessage{opOf(map[string]any{ |
| 153 | "op": "register_asset", "id": assetID, "ref": ref, |
| 154 | "width": cfg.Width, "height": cfg.Height, "alt": alt, |
| 155 | })}, nil |
| 156 | } |
| 157 | _, _, err = a.applyAgentOpsFrom(r.Context(), &d, p.actor(), build, g) |
| 158 | switch { |
| 159 | case err == nil: |
| 160 | a.writeJSON(w, http.StatusCreated, map[string]any{"id": assetID, "ref": ref, "width": cfg.Width, "height": cfg.Height}) |
| 161 | case errors.Is(err, errAssetKnown): |
| 162 | a.writeJSON(w, http.StatusOK, map[string]any{"id": existing, "ref": ref, "width": cfg.Width, "height": cfg.Height}) |
| 163 | default: |
| 164 | a.apiOpsFailed(w, d, err) |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | // opOf is one op of a batch, from the values it carries. |
| 169 | func opOf(fields map[string]any) map[string]json.RawMessage { |
| 170 | op := make(map[string]json.RawMessage, len(fields)) |
| 171 | for k, v := range fields { |
| 172 | op[k], _ = json.Marshal(v) |
| 173 | } |
| 174 | return op |
| 175 | } |
| 176 | |