| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "net/http" |
| 6 | "strings" |
| 7 | |
| 8 | "github.com/go-chi/chi/v5" |
| 9 | ) |
| 10 | |
| 11 | // Remove from Mapa (§3.3): its own confirm page, as every destructive |
| 12 | // action has, and the removal. Anyone who may not remove the image gets |
| 13 | // the app's 404 from both, as for an id that does not exist (IMG1). |
| 14 | |
| 15 | // removeData is templates/image_remove.html's data. |
| 16 | type removeData struct { |
| 17 | Image Image |
| 18 | Action string |
| 19 | Back string |
| 20 | Hidden [][2]string |
| 21 | } |
| 22 | |
| 23 | // backTo is a same-app path to return to, by the rule every return in |
| 24 | // Mapa uses (safeReturn), or Today (Fable L7). |
| 25 | func backTo(raw string) string { return firstOf(safeReturn(raw), "/") } |
| 26 | |
| 27 | func (app *app) confirmRemoveImage(writer http.ResponseWriter, |
| 28 | request *http.Request) { |
| 29 | viewer, err := app.viewer(request) |
| 30 | if err != nil { |
| 31 | app.fail(writer, request, err) |
| 32 | return |
| 33 | } |
| 34 | image, err := app.store.RemovableImage(request.Context(), viewer, |
| 35 | chi.URLParam(request, "id")) |
| 36 | if errors.Is(err, ErrNoImage) { |
| 37 | notFound(writer, request) |
| 38 | return |
| 39 | } |
| 40 | if err != nil { |
| 41 | app.fail(writer, request, err) |
| 42 | return |
| 43 | } |
| 44 | back := backTo(request.URL.Query().Get("back")) |
| 45 | app.show(writer, request, http.StatusOK, "image_remove", view{ |
| 46 | Title: "Remove this image", Nav: nav(""), Viewer: viewer, |
| 47 | Data: removeData{Image: image, Action: request.URL.Path, |
| 48 | Back: back, Hidden: [][2]string{{"back", back}}}}) |
| 49 | } |
| 50 | |
| 51 | func (app *app) removeImage(writer http.ResponseWriter, |
| 52 | request *http.Request) { |
| 53 | address, _ := app.identity(request) |
| 54 | err := app.store.RemoveImage(request.Context(), address, |
| 55 | chi.URLParam(request, "id")) |
| 56 | if errors.Is(err, ErrNoImage) { |
| 57 | notFound(writer, request) |
| 58 | return |
| 59 | } |
| 60 | if err != nil { |
| 61 | app.fail(writer, request, err) |
| 62 | return |
| 63 | } |
| 64 | back := backTo(request.PostFormValue("back")) |
| 65 | separator := "?" |
| 66 | if strings.Contains(back, "?") { |
| 67 | separator = "&" |
| 68 | } |
| 69 | seeOther(writer, request, back+separator+"done=image-removed") |
| 70 | } |
| 71 | |