summaryrefslogtreecommitdiffstats
path: root/internal/media/handler.go
blob: 3cca2bd8c8ee513c0fd9bcfa6d92b6e4fabf80ef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package media

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

const (
	maxUploadSize = 20 << 20 // 20 MB
	maxWidth      = 3000
)

// allowedMIMEs maps detected content types to canonical file extensions.
var allowedMIMEs = map[string]string{
	"image/jpeg": ".jpg",
	"image/png":  ".png",
	"image/gif":  ".gif",
	"image/webp": ".webp",
}

// MediaHandler handles image uploads and on-the-fly image serving.
type MediaHandler struct {
	StorageDir string
}

// NewMediaHandler returns a MediaHandler that stores files in storageDir.
func NewMediaHandler(storageDir string) *MediaHandler {
	return &MediaHandler{StorageDir: storageDir}
}

// HandleUpload handles POST /admin/upload/image.
// Expects multipart/form-data with an "image" field.
// Returns EditorJS-compatible JSON: {"success":1,"file":{"url":"/media/<uuid>.webp"}}
func (h *MediaHandler) HandleUpload(c *gin.Context) {
	c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxUploadSize)

	file, _, err := c.Request.FormFile("image")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"success": 0, "error": err.Error()})
		return
	}
	defer file.Close()

	// Sniff MIME type from first 512 bytes
	sniff := make([]byte, 512)
	n, _ := file.Read(sniff)
	mimeType := http.DetectContentType(sniff[:n])
	ext, ok := allowedMIMEs[mimeType]
	if !ok {
		c.JSON(http.StatusBadRequest, gin.H{"success": 0, "error": "unsupported image type: " + mimeType})
		return
	}

	// Rewind so the full file is copied to disk
	if seeker, ok := file.(io.Seeker); ok {
		if _, err := seeker.Seek(0, io.SeekStart); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"success": 0, "error": "seek error"})
			return
		}
	}

	if err := os.MkdirAll(h.StorageDir, 0755); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"success": 0, "error": "storage error"})
		return
	}

	id := uuid.New().String()
	destPath := filepath.Join(h.StorageDir, id+ext)

	out, err := os.Create(destPath)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"success": 0, "error": "storage error"})
		return
	}
	defer out.Close()

	if _, err := io.Copy(out, file); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"success": 0, "error": "write error"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": 1,
		"file":    gin.H{"url": "/media/" + id + ".webp"},
	})
}

// HandleServe handles GET /media/*filepath.
// Format is determined by the file extension (.webp or .jpg/.jpeg).
// The optional ?w=<pixels> query param resizes the image (clamped to 3000; error if <= 0).
func (h *MediaHandler) HandleServe(c *gin.Context) {
	filename := strings.TrimPrefix(c.Param("filepath"), "/")
	ext := strings.ToLower(filepath.Ext(filename))
	base := strings.TrimSuffix(filename, filepath.Ext(filename))

	var format, contentType string
	switch ext {
	case ".webp":
		format, contentType = "webp", "image/webp"
	case ".jpg", ".jpeg":
		format, contentType = "jpeg", "image/jpeg"
	default:
		c.AbortWithStatus(http.StatusNotFound)
		return
	}

	width := 0
	if wStr := c.Query("w"); wStr != "" {
		w, err := strconv.Atoi(wStr)
		if err != nil || w <= 0 {
			c.AbortWithStatus(http.StatusBadRequest)
			return
		}
		if w > maxWidth {
			w = maxWidth
		}
		width = w
	}

	cacheName := cacheKey(base, width, format)
	cachePath := filepath.Join(h.StorageDir, cacheName)

	// Cache hit: serve the existing variant directly
	if f, err := os.Open(cachePath); err == nil {
		defer f.Close()
		info, _ := os.Stat(cachePath)
		c.Header("Content-Type", contentType)
		http.ServeContent(c.Writer, c.Request, cacheName, info.ModTime(), f)
		return
	}

	origPath, err := findOriginal(h.StorageDir, base)
	if err != nil {
		c.AbortWithStatus(http.StatusNotFound)
		return
	}

	// Skip processing if format matches original and no resize is requested
	origExt := strings.ToLower(filepath.Ext(origPath))
	sameFormat := origExt == ext ||
		(origExt == ".jpg" && ext == ".jpeg") ||
		(origExt == ".jpeg" && ext == ".jpg")
	if width == 0 && sameFormat {
		f, err := os.Open(origPath)
		if err != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
		defer f.Close()
		info, _ := os.Stat(origPath)
		c.Header("Content-Type", contentType)
		http.ServeContent(c.Writer, c.Request, filename, info.ModTime(), f)
		return
	}

	result, err := ConvertAndResize(origPath, width, format)
	if err != nil {
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	// Atomic cache write — concurrent writers are harmless (last rename wins)
	tmp := cachePath + ".tmp"
	if err := os.WriteFile(tmp, result, 0644); err == nil {
		_ = os.Rename(tmp, cachePath)
	}

	c.Header("Content-Type", contentType)
	c.Data(http.StatusOK, contentType, result)
}

// cacheKey returns the filename for a processed image variant.
//   - No width: "<base>.webp" / "<base>.jpg"
//   - With width: "<base>_<width>w.webp" / "<base>_<width>w.jpg"
func cacheKey(base string, width int, format string) string {
	ext := ".webp"
	if format == "jpeg" {
		ext = ".jpg"
	}
	if width > 0 {
		return fmt.Sprintf("%s_%dw%s", base, width, ext)
	}
	return base + ext
}

// findOriginal finds the original upload file for a given UUID base name.
// Cache variants (which contain '_' before the extension) are excluded.
func findOriginal(dir, base string) (string, error) {
	matches, err := filepath.Glob(filepath.Join(dir, base+".*"))
	if err != nil {
		return "", err
	}
	for _, m := range matches {
		name := filepath.Base(m)
		nameBase := strings.TrimSuffix(name, filepath.Ext(name))
		if !strings.Contains(nameBase, "_") {
			return m, nil
		}
	}
	return "", fmt.Errorf("original not found for %q in %s", base, dir)
}