|
| 1 | +package httpapi |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "image" |
| 9 | + "image/gif" |
| 10 | + "image/jpeg" |
| 11 | + "image/png" |
| 12 | + "io" |
| 13 | + "net/http" |
| 14 | + "os" |
| 15 | + "path/filepath" |
| 16 | + "strconv" |
| 17 | + "strings" |
| 18 | + "time" |
| 19 | + |
| 20 | + "scrumboy/internal/store" |
| 21 | +) |
| 22 | + |
| 23 | +const ( |
| 24 | + wallpaperPrefKey = "wallpaper" |
| 25 | + wallpaperMaxBytes = 6 << 20 // 6 MiB raw multipart |
| 26 | + wallpaperJPEGQuality = 85 |
| 27 | + wallpaperMaxDim = 2560 |
| 28 | +) |
| 29 | + |
| 30 | +// userWallpaperFilePath returns the on-disk path for the user's normalized JPEG wallpaper. |
| 31 | +func (s *Server) userWallpaperFilePath(userID int64) string { |
| 32 | + return filepath.Join(s.dataDir, "user-wallpapers", fmt.Sprintf("%d.jpg", userID)) |
| 33 | +} |
| 34 | + |
| 35 | +func (s *Server) ensureWallpaperDir() error { |
| 36 | + dir := filepath.Join(s.dataDir, "user-wallpapers") |
| 37 | + return os.MkdirAll(dir, 0o700) |
| 38 | +} |
| 39 | + |
| 40 | +func (s *Server) deleteUserWallpaperFile(userID int64) { |
| 41 | + path := s.userWallpaperFilePath(userID) |
| 42 | + _ = os.Remove(path) |
| 43 | +} |
| 44 | + |
| 45 | +// handleUserWallpaper routes DELETE /api/user/wallpaper, GET/POST /api/user/wallpaper/image |
| 46 | +// rest is like ["wallpaper"] or ["wallpaper","image"] (path after /api/user/). |
| 47 | +func (s *Server) handleUserWallpaper(w http.ResponseWriter, r *http.Request, userID int64, rest []string) { |
| 48 | + if s.dataDir == "" { |
| 49 | + writeError(w, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "wallpaper storage not configured", nil) |
| 50 | + return |
| 51 | + } |
| 52 | + |
| 53 | + ctx := s.requestContext(r) |
| 54 | + |
| 55 | + switch { |
| 56 | + case len(rest) == 1 && rest[0] == "wallpaper" && r.Method == http.MethodDelete: |
| 57 | + s.deleteUserWallpaper(w, r, ctx, userID) |
| 58 | + return |
| 59 | + |
| 60 | + case len(rest) == 2 && rest[0] == "wallpaper" && rest[1] == "image" && r.Method == http.MethodGet: |
| 61 | + s.serveUserWallpaperImage(w, r, ctx, userID) |
| 62 | + return |
| 63 | + |
| 64 | + case len(rest) == 2 && rest[0] == "wallpaper" && rest[1] == "image" && r.Method == http.MethodPost: |
| 65 | + s.uploadUserWallpaperImage(w, r, ctx, userID) |
| 66 | + return |
| 67 | + |
| 68 | + default: |
| 69 | + writeError(w, http.StatusNotFound, "NOT_FOUND", "not found", nil) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +func (s *Server) wallpaperPrefModeImage(ctx context.Context, userID int64) (store.WallpaperPref, bool) { |
| 74 | + raw, err := s.store.GetUserPreference(ctx, userID, wallpaperPrefKey) |
| 75 | + if err != nil || strings.TrimSpace(raw) == "" { |
| 76 | + return store.WallpaperPref{}, false |
| 77 | + } |
| 78 | + p, err := store.ParseWallpaperPref(raw) |
| 79 | + if err != nil || p.Mode != "image" { |
| 80 | + return store.WallpaperPref{}, false |
| 81 | + } |
| 82 | + return p, true |
| 83 | +} |
| 84 | + |
| 85 | +func (s *Server) serveUserWallpaperImage(w http.ResponseWriter, r *http.Request, ctx context.Context, userID int64) { |
| 86 | + p, ok := s.wallpaperPrefModeImage(ctx, userID) |
| 87 | + if !ok { |
| 88 | + writeError(w, http.StatusNotFound, "NOT_FOUND", "no wallpaper image", nil) |
| 89 | + return |
| 90 | + } |
| 91 | + path := s.userWallpaperFilePath(userID) |
| 92 | + f, err := os.Open(path) |
| 93 | + if err != nil { |
| 94 | + if os.IsNotExist(err) { |
| 95 | + writeError(w, http.StatusNotFound, "NOT_FOUND", "wallpaper file missing", nil) |
| 96 | + return |
| 97 | + } |
| 98 | + writeInternal(w, err) |
| 99 | + return |
| 100 | + } |
| 101 | + defer f.Close() |
| 102 | + |
| 103 | + w.Header().Set("Content-Type", "image/jpeg") |
| 104 | + w.Header().Set("Cache-Control", "private, max-age=3600") |
| 105 | + w.Header().Set("ETag", strconv.FormatInt(p.Rev, 10)) |
| 106 | + if inm := r.Header.Get("If-None-Match"); inm != "" && inm == strconv.FormatInt(p.Rev, 10) { |
| 107 | + w.WriteHeader(http.StatusNotModified) |
| 108 | + return |
| 109 | + } |
| 110 | + w.WriteHeader(http.StatusOK) |
| 111 | + _, _ = io.Copy(w, f) |
| 112 | +} |
| 113 | + |
| 114 | +func decodeWallpaperUpload(data []byte, contentType string) (image.Image, error) { |
| 115 | + ct := strings.ToLower(strings.TrimSpace(contentType)) |
| 116 | + r := bytes.NewReader(data) |
| 117 | + switch { |
| 118 | + case strings.Contains(ct, "jpeg"), strings.Contains(ct, "jpg"): |
| 119 | + return jpeg.Decode(r) |
| 120 | + case strings.Contains(ct, "png"): |
| 121 | + return png.Decode(r) |
| 122 | + case strings.Contains(ct, "gif"): |
| 123 | + return gif.Decode(r) |
| 124 | + default: |
| 125 | + return nil, fmt.Errorf("use JPEG, PNG, or GIF") |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +func encodeWallpaperJPEG(img image.Image) (*bytes.Buffer, error) { |
| 130 | + bounds := img.Bounds() |
| 131 | + dx := bounds.Dx() |
| 132 | + dy := bounds.Dy() |
| 133 | + if dx <= 0 || dy <= 0 { |
| 134 | + return nil, fmt.Errorf("invalid dimensions") |
| 135 | + } |
| 136 | + if dx > wallpaperMaxDim || dy > wallpaperMaxDim { |
| 137 | + scale := float64(wallpaperMaxDim) / float64(max(dx, dy)) |
| 138 | + newW := int(float64(dx) * scale) |
| 139 | + newH := int(float64(dy) * scale) |
| 140 | + if newW < 1 { |
| 141 | + newW = 1 |
| 142 | + } |
| 143 | + if newH < 1 { |
| 144 | + newH = 1 |
| 145 | + } |
| 146 | + img = resizeNearest(img, newW, newH) |
| 147 | + } |
| 148 | + var buf bytes.Buffer |
| 149 | + if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: wallpaperJPEGQuality}); err != nil { |
| 150 | + return nil, err |
| 151 | + } |
| 152 | + return &buf, nil |
| 153 | +} |
| 154 | + |
| 155 | +func max(a, b int) int { |
| 156 | + if a > b { |
| 157 | + return a |
| 158 | + } |
| 159 | + return b |
| 160 | +} |
| 161 | + |
| 162 | +// resizeNearest simple resize for large photos (good enough for background wallpaper). |
| 163 | +func resizeNearest(src image.Image, newW, newH int) image.Image { |
| 164 | + b := src.Bounds() |
| 165 | + dst := image.NewRGBA(image.Rect(0, 0, newW, newH)) |
| 166 | + xratio := float64(b.Dx()) / float64(newW) |
| 167 | + yratio := float64(b.Dy()) / float64(newH) |
| 168 | + for y := 0; y < newH; y++ { |
| 169 | + for x := 0; x < newW; x++ { |
| 170 | + sx := int(float64(x) * xratio) |
| 171 | + sy := int(float64(y) * yratio) |
| 172 | + if sx >= b.Dx() { |
| 173 | + sx = b.Dx() - 1 |
| 174 | + } |
| 175 | + if sy >= b.Dy() { |
| 176 | + sy = b.Dy() - 1 |
| 177 | + } |
| 178 | + dst.Set(x, y, src.At(b.Min.X+sx, b.Min.Y+sy)) |
| 179 | + } |
| 180 | + } |
| 181 | + return dst |
| 182 | +} |
| 183 | + |
| 184 | +func (s *Server) uploadUserWallpaperImage(w http.ResponseWriter, r *http.Request, ctx context.Context, userID int64) { |
| 185 | + if err := r.ParseMultipartForm(wallpaperMaxBytes); err != nil { |
| 186 | + writeError(w, http.StatusBadRequest, "BAD_REQUEST", "invalid multipart form", nil) |
| 187 | + return |
| 188 | + } |
| 189 | + file, hdr, err := r.FormFile("file") |
| 190 | + if err != nil { |
| 191 | + writeError(w, http.StatusBadRequest, "BAD_REQUEST", "missing file field", map[string]any{"field": "file"}) |
| 192 | + return |
| 193 | + } |
| 194 | + defer file.Close() |
| 195 | + |
| 196 | + ct := hdr.Header.Get("Content-Type") |
| 197 | + if ct == "" { |
| 198 | + ct = "application/octet-stream" |
| 199 | + } |
| 200 | + if !strings.HasPrefix(strings.ToLower(ct), "image/") { |
| 201 | + writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "file must be an image", map[string]any{"field": "file"}) |
| 202 | + return |
| 203 | + } |
| 204 | + |
| 205 | + data, err := io.ReadAll(io.LimitReader(file, wallpaperMaxBytes)) |
| 206 | + if err != nil { |
| 207 | + writeInternal(w, err) |
| 208 | + return |
| 209 | + } |
| 210 | + img, err := decodeWallpaperUpload(data, ct) |
| 211 | + if err != nil { |
| 212 | + writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", err.Error(), map[string]any{"field": "file"}) |
| 213 | + return |
| 214 | + } |
| 215 | + |
| 216 | + buf, err := encodeWallpaperJPEG(img) |
| 217 | + if err != nil { |
| 218 | + writeInternal(w, err) |
| 219 | + return |
| 220 | + } |
| 221 | + if buf.Len() > 3<<20 { |
| 222 | + writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "processed image too large", nil) |
| 223 | + return |
| 224 | + } |
| 225 | + |
| 226 | + if err := s.ensureWallpaperDir(); err != nil { |
| 227 | + writeInternal(w, err) |
| 228 | + return |
| 229 | + } |
| 230 | + path := s.userWallpaperFilePath(userID) |
| 231 | + tmp := path + ".tmp" |
| 232 | + if err := os.WriteFile(tmp, buf.Bytes(), 0o600); err != nil { |
| 233 | + writeInternal(w, err) |
| 234 | + return |
| 235 | + } |
| 236 | + if err := os.Rename(tmp, path); err != nil { |
| 237 | + _ = os.Remove(tmp) |
| 238 | + writeInternal(w, err) |
| 239 | + return |
| 240 | + } |
| 241 | + |
| 242 | + rev := time.Now().UTC().UnixMilli() |
| 243 | + pref := store.WallpaperPref{V: store.WallpaperPrefVersion, Mode: "image", Rev: rev} |
| 244 | + b, err := json.Marshal(pref) |
| 245 | + if err != nil { |
| 246 | + writeInternal(w, err) |
| 247 | + return |
| 248 | + } |
| 249 | + if err := s.store.SetUserPreference(ctx, userID, wallpaperPrefKey, string(b)); err != nil { |
| 250 | + writeStoreErr(w, err, true) |
| 251 | + return |
| 252 | + } |
| 253 | + |
| 254 | + writeJSON(w, http.StatusOK, map[string]any{"rev": rev, "mode": "image"}) |
| 255 | +} |
| 256 | + |
| 257 | +func (s *Server) deleteUserWallpaper(w http.ResponseWriter, r *http.Request, ctx context.Context, userID int64) { |
| 258 | + s.deleteUserWallpaperFile(userID) |
| 259 | + off := store.WallpaperPref{V: store.WallpaperPrefVersion, Mode: "off"} |
| 260 | + b, err := json.Marshal(off) |
| 261 | + if err != nil { |
| 262 | + writeInternal(w, err) |
| 263 | + return |
| 264 | + } |
| 265 | + if err := s.store.SetUserPreference(ctx, userID, wallpaperPrefKey, string(b)); err != nil { |
| 266 | + writeStoreErr(w, err, true) |
| 267 | + return |
| 268 | + } |
| 269 | + w.WriteHeader(http.StatusNoContent) |
| 270 | +} |
0 commit comments