| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "net/http" |
| 6 | "strings" |
| 7 | |
| 8 | "github.com/go-chi/chi/v5" |
| 9 | |
| 10 | "amadan.net/oficina/mapa/internal/mapa/imagefile" |
| 11 | "amadan.net/oficina/mapa/internal/mapa/locale" |
| 12 | "amadan.net/oficina/mapa/internal/mapa/markup" |
| 13 | ) |
| 14 | |
| 15 | // The images' routes (images spec §6): the upload, scoped serving, the |
| 16 | // copy a paste makes, and Remove with its confirm page. |
| 17 | |
| 18 | func (app *app) imageRoutes(router chi.Router) { |
| 19 | router.Post("/images", app.uploadImage) |
| 20 | router.Post("/images/copy", app.copyImages) |
| 21 | router.Get("/i/{id}", app.serveImage) |
| 22 | router.Get("/i/{id}/remove", app.confirmRemoveImage) |
| 23 | router.Post("/i/{id}/remove", app.removeImage) |
| 24 | } |
| 25 | |
| 26 | // uploadSlack is a multipart request's room beyond its file: the |
| 27 | // boundaries and headers, and the editor's few fields. |
| 28 | const uploadSlack = 64 << 10 |
| 29 | |
| 30 | // imageReply is an upload's or a copy's answer to the editor. |
| 31 | type imageReply struct { |
| 32 | ID string `json:"id"` |
| 33 | Src string `json:"src"` |
| 34 | Width int `json:"width"` |
| 35 | Height int `json:"height"` |
| 36 | } |
| 37 | |
| 38 | func replyOf(image Image) imageReply { |
| 39 | return imageReply{ID: image.PublicID, |
| 40 | Src: markup.ImagePrefix + image.PublicID, |
| 41 | Width: image.Width, Height: image.Height} |
| 42 | } |
| 43 | |
| 44 | // uploadImage is POST /images: one file, multipart field "file", as |
| 45 | // JSON. The scriptless Markdown screen's Upload and insert posts to its |
| 46 | // own form's action instead (insertUpload), which re-renders it. |
| 47 | func (app *app) uploadImage(writer http.ResponseWriter, |
| 48 | request *http.Request) { |
| 49 | image, err := app.receiveImage(writer, request, 0) |
| 50 | if err != nil { |
| 51 | app.refuseImage(writer, request, err) |
| 52 | return |
| 53 | } |
| 54 | answer(writer, replyOf(image)) |
| 55 | } |
| 56 | |
| 57 | // imageRefusals is each refusal's status and sentence (§3.4, §5). |
| 58 | var imageRefusals = []struct { |
| 59 | err error |
| 60 | status int |
| 61 | say string |
| 62 | }{ |
| 63 | {ErrImageType, http.StatusUnsupportedMediaType, |
| 64 | "Mapa takes PNG, JPEG, GIF and WebP images."}, |
| 65 | {ErrImageTooLarge, http.StatusRequestEntityTooLarge, |
| 66 | "An image can be at most 10 MB."}, |
| 67 | {ErrNoImageStore, http.StatusServiceUnavailable, |
| 68 | "Images aren't set up in Mapa yet."}, |
| 69 | {ErrImageBusy, http.StatusServiceUnavailable, |
| 70 | "Mapa is busy with other images. Try again in a moment."}, |
| 71 | {ErrStorageFull, http.StatusInsufficientStorage, |
| 72 | "Mapa's storage is full. Ask whoever runs your team's Oficina."}, |
| 73 | {ErrNoImage, http.StatusNotFound, "That image isn't available."}, |
| 74 | {errNoFile, http.StatusUnprocessableEntity, errNoFile.Error()}, |
| 75 | {errUnreadable, http.StatusBadRequest, |
| 76 | "The form could not be read. Try again."}, |
| 77 | } |
| 78 | |
| 79 | // imageRefusal is err's status and sentence, its numbers written in |
| 80 | // dates's locale (level-up build note 85), or false for a failure. |
| 81 | func imageRefusal(err error, dates *locale.Locale) (int, string, bool) { |
| 82 | var quota quotaError |
| 83 | if errors.As(err, "a) { |
| 84 | return http.StatusInsufficientStorage, quota.say(dates), true |
| 85 | } |
| 86 | if errors.Is(err, ErrImageDimensions) { |
| 87 | return http.StatusUnprocessableEntity, "That image is too " + |
| 88 | "large: at most " + dates.Number(imagefile.MaxSide) + " pixels " + |
| 89 | "on a side, and " + dates.Number(imagefile.MaxPixels/1_000_000) + |
| 90 | " megapixels in all.", true |
| 91 | } |
| 92 | for _, refusal := range imageRefusals { |
| 93 | if errors.Is(err, refusal.err) { |
| 94 | return refusal.status, refusal.say, true |
| 95 | } |
| 96 | } |
| 97 | return 0, "", false |
| 98 | } |
| 99 | |
| 100 | // refuseImage answers a refused upload or copy as JSON. A wait that ran |
| 101 | // out says when to try again. |
| 102 | func (app *app) refuseImage(writer http.ResponseWriter, |
| 103 | request *http.Request, err error) { |
| 104 | status, say, ok := imageRefusal(err, localeIn(request)) |
| 105 | if !ok { |
| 106 | app.logger.Error("image failed", "path", request.URL.Path, |
| 107 | "err", err) |
| 108 | status, say = http.StatusInternalServerError, |
| 109 | "The image could not be stored. Try again." |
| 110 | } |
| 111 | if errors.Is(err, ErrImageBusy) { |
| 112 | writer.Header().Set("Retry-After", "5") |
| 113 | } |
| 114 | refuseJSON(writer, status, say) |
| 115 | } |
| 116 | |
| 117 | // maxCopies is how many images one paste may copy at once. |
| 118 | const maxCopies = 32 |
| 119 | |
| 120 | // copyImages is POST /images/copy: ids in the body, as "id" fields, |
| 121 | // answered {id: {id, src, width, height}} for each the person may read. |
| 122 | // An id they may not read is left out, as one that does not exist is. |
| 123 | func (app *app) copyImages(writer http.ResponseWriter, |
| 124 | request *http.Request) { |
| 125 | if err := request.ParseForm(); err != nil { |
| 126 | notFound(writer, request) |
| 127 | return |
| 128 | } |
| 129 | ids := request.PostForm["id"] |
| 130 | if len(ids) > maxCopies { |
| 131 | refuseJSON(writer, http.StatusUnprocessableEntity, |
| 132 | "Paste at most 32 images at once.") |
| 133 | return |
| 134 | } |
| 135 | address, _ := app.identity(request) |
| 136 | out, err := app.copyEach(request, byAddress(address), ids) |
| 137 | if err != nil { |
| 138 | app.refuseImage(writer, request, err) |
| 139 | return |
| 140 | } |
| 141 | answer(writer, out) |
| 142 | } |
| 143 | |
| 144 | // copyEach copies each id once (Fable L2). When one copy is refused, |
| 145 | // the copies made before it are removed with it: a paste copies all its |
| 146 | // images or none. |
| 147 | func (app *app) copyEach(request *http.Request, who person, |
| 148 | ids []string) (map[string]imageReply, error) { |
| 149 | out := map[string]imageReply{} |
| 150 | made := copied{ids: map[string]string{}} |
| 151 | for _, id := range ids { |
| 152 | if _, done := out[id]; done { |
| 153 | continue |
| 154 | } |
| 155 | image, err := app.store.copyImage(request.Context(), who, id, |
| 156 | uploadWait) |
| 157 | switch { |
| 158 | case errors.Is(err, ErrNoImage): |
| 159 | continue |
| 160 | case err != nil: |
| 161 | app.store.dropCopies(request.Context(), who, made) |
| 162 | return nil, err |
| 163 | } |
| 164 | out[id], made.ids[id] = replyOf(image), image.PublicID |
| 165 | } |
| 166 | return out, nil |
| 167 | } |
| 168 | |
| 169 | // serveImage is GET /i/{id} (§1.4): scope first, then a 304 for the |
| 170 | // browser's own copy, then the bytes, read, checked, opened and |
| 171 | // written with headers that let them be nothing but an image. |
| 172 | func (app *app) serveImage(writer http.ResponseWriter, |
| 173 | request *http.Request) { |
| 174 | viewer, err := app.viewer(request) |
| 175 | if err != nil { |
| 176 | app.fail(writer, request, err) |
| 177 | return |
| 178 | } |
| 179 | id := chi.URLParam(request, "id") |
| 180 | row, err := app.store.ReadableImage(request.Context(), viewer, id) |
| 181 | if errors.Is(err, ErrNoImage) { |
| 182 | notFound(writer, request) |
| 183 | return |
| 184 | } |
| 185 | if err != nil { |
| 186 | app.fail(writer, request, err) |
| 187 | return |
| 188 | } |
| 189 | tag := `"` + id + `"` |
| 190 | header := writer.Header() |
| 191 | header.Set("ETag", tag) |
| 192 | header.Set("Cache-Control", "private, max-age=3600, immutable") |
| 193 | if matches(request.Header.Get("If-None-Match"), tag) { |
| 194 | writer.WriteHeader(http.StatusNotModified) |
| 195 | return |
| 196 | } |
| 197 | app.writeImage(writer, request, row) |
| 198 | } |
| 199 | |
| 200 | // matches is If-None-Match naming tag, or *. |
| 201 | func matches(header, tag string) bool { |
| 202 | for _, each := range strings.Split(header, ",") { |
| 203 | each = strings.TrimPrefix(strings.TrimSpace(each), "W/") |
| 204 | if each == tag || each == "*" { |
| 205 | return true |
| 206 | } |
| 207 | } |
| 208 | return false |
| 209 | } |
| 210 | |
| 211 | func (app *app) writeImage(writer http.ResponseWriter, |
| 212 | request *http.Request, row ImageRow) { |
| 213 | picture, kind, err := app.store.ImageBytes(request.Context(), row) |
| 214 | if errors.Is(err, ErrImageBusy) { |
| 215 | writer.Header().Set("Retry-After", "5") |
| 216 | writer.Header().Set("Cache-Control", "no-store") |
| 217 | http.Error(writer, "busy", http.StatusServiceUnavailable) |
| 218 | return |
| 219 | } |
| 220 | if err != nil { |
| 221 | writer.Header().Set("Cache-Control", "no-store") |
| 222 | app.fail(writer, request, err) |
| 223 | return |
| 224 | } |
| 225 | header := writer.Header() |
| 226 | header.Set("Content-Type", kind) |
| 227 | header.Set("X-Content-Type-Options", "nosniff") |
| 228 | header.Set("Content-Security-Policy", "default-src 'none'; sandbox") |
| 229 | header.Set("Content-Disposition", "inline") |
| 230 | header.Set("Cross-Origin-Resource-Policy", "same-origin") |
| 231 | _, _ = writer.Write(picture) |
| 232 | } |
| 233 | |