This repository has been archived by the owner on Jun 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
269 lines (222 loc) · 6.67 KB
/
main.go
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package main
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/davidbyttow/govips/v2/vips"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/h2non/filetype"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
log "github.com/sirupsen/logrus"
"io"
"mime/multipart"
"net/http"
"os"
"strconv"
"time"
)
const TooLargeErrorMessage = "http: request body too large"
const JpegQuality = 85
var minioClient *minio.Client
var bucketName string
var signatureSecret string
var uploadSizeLimitBytes int64
var uploadResolutionLimitPixels int64
var port = os.Getenv("PORT")
func main() {
initLogger()
initOptions()
initVips()
defer vips.Shutdown()
initMinioClient()
log.Infof("Listening on port %s", port)
if err := http.ListenAndServe(":"+port, createHandler()); err != nil {
log.Panicln(err)
}
}
func initOptions() {
bucketName = os.Getenv("MINIO_BUCKET_NAME")
signatureSecret = os.Getenv("SIGNATURE_SECRET")
uploadSizeLimitBytes = loadInteger("UPLOAD_LIMIT_MEGABYTES") * 1024 * 1024
uploadResolutionLimitPixels = loadInteger("UPLOAD_LIMIT_MEGAPIXELS") * 1000 * 1000
log.Infof("Bucket name: %s", bucketName)
log.Infof("Upload size limit bytes: %d", uploadSizeLimitBytes)
log.Infof("Upload resolution limit pixels: %d", uploadResolutionLimitPixels)
}
func loadInteger(key string) int64 {
value, err := strconv.ParseInt(os.Getenv(key), 10, 64)
if err != nil {
log.Panicf("Could not parse env variable %s: %s", key, err)
}
return value
}
func initVips() {
vips.LoggingSettings(func(messageDomain string, messageLevel vips.LogLevel, message string) {
msg := fmt.Sprintf("[%s] %v", messageDomain, message)
switch messageLevel {
case vips.LogLevelError:
case vips.LogLevelCritical:
log.Error(msg)
case vips.LogLevelWarning:
log.Warn(msg)
case vips.LogLevelMessage:
case vips.LogLevelInfo:
log.Info(msg)
case vips.LogLevelDebug:
log.Debug(msg)
}
}, vips.LogLevelInfo)
vips.Startup(nil)
}
func initLogger() {
log.SetLevel(log.DebugLevel)
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
ForceColors: os.Getenv("ENVIRONMENT") != "production",
DisableLevelTruncation: true,
})
}
func createHandler() http.Handler {
r := mux.NewRouter()
r.HandleFunc("/photo/{year:[0-9]{4}}/{month:[0-9]{2}}/{fileName}", uploadHandler).Methods("PUT")
r.Use(loggingMiddleware)
r.Use(signatureMiddleware)
var origin string
if os.Getenv("ENVIRONMENT") == "production" {
origin = "https://forum.fibra.click"
} else {
origin = "*"
}
return handlers.CORS(
handlers.AllowedMethods([]string{"PUT"}),
handlers.AllowedOrigins([]string{origin}),
handlers.MaxAge(3600),
)(r)
}
func initMinioClient() {
minioEndpoint := os.Getenv("MINIO_ENDPOINT")
minioAccessKey := os.Getenv("MINIO_ACCESS_KEY")
minioSecretKey := os.Getenv("MINIO_SECRET_KEY")
var err error
minioClient, err = minio.New(minioEndpoint, &minio.Options{
Creds: credentials.NewStaticV4(minioAccessKey, minioSecretKey, ""),
})
if err != nil {
log.Panicln(err)
}
}
func loggingMiddleware(next http.Handler) http.Handler {
// TODO: simplify output
return handlers.CombinedLoggingHandler(log.StandardLogger().Writer(), next)
}
func signatureMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
expiresString := r.URL.Query().Get("expires")
signature := r.URL.Query().Get("signature")
if expiresString == "" || signature == "" {
http.Error(w, "Missing signature", http.StatusUnauthorized)
return
}
now := time.Now().Unix()
expires, err := strconv.ParseInt(expiresString, 10, 64)
if err != nil || now > expires {
http.Error(w, "Signature expired", http.StatusUnauthorized)
return
}
h := hmac.New(sha256.New, []byte(signatureSecret))
h.Write([]byte(expiresString))
h.Write([]byte(r.URL.Path))
sha := hex.EncodeToString(h.Sum(nil))
if sha != signature {
http.Error(w, "Invalid signature", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
r.Body = http.MaxBytesReader(w, r.Body, uploadSizeLimitBytes)
formFile, _, err := r.FormFile("file")
if err != nil {
if err.Error() == TooLargeErrorMessage {
log.Errorf("Uploaded file is larger than %d bytes", uploadSizeLimitBytes)
http.Error(w, "", http.StatusRequestEntityTooLarge)
} else {
log.Errorf("Could not get file from body: %s", err)
http.Error(w, "", http.StatusBadRequest)
}
return
}
defer formFile.Close()
if !isSupportedFileType(formFile) {
http.Error(w, "", http.StatusUnsupportedMediaType)
return
}
img, err := vips.NewImageFromReader(formFile)
if err != nil {
log.Errorf("Could not read image file: %s", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
resolution := img.Width() * img.Height()
if int64(resolution) > uploadResolutionLimitPixels {
log.Errorf("Uploaded file exceeds resolution limit: %d > %d", resolution, uploadResolutionLimitPixels)
http.Error(w, "", http.StatusRequestEntityTooLarge)
return
}
if err := img.AutoRotate(); err != nil {
log.Errorf("Could not rotate image: %s", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
// Basically convert the color space to sRGB
if err := img.OptimizeICCProfile(); err != nil {
log.Errorf("Could not optimize ICC profile: %s", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
// Remove metadata but keep the color profile
if err := img.RemoveMetadata(); err != nil {
log.Errorf("Could not remove metadata: %s", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
ep := vips.NewJpegExportParams()
ep.Quality = JpegQuality
ep.OvershootDeringing = true
// Disable progressive DCT, produces slightly larger file size but with faster encoding/decoding
ep.Interlace = false
compressedImageBytes, _, err := img.ExportJpeg(ep)
reader := bytes.NewReader(compressedImageBytes)
key := params["year"] + "/" + params["month"] + "/" + params["fileName"]
// TODO: check if object already exists
_, err = minioClient.PutObject(
context.Background(),
bucketName,
key,
reader,
reader.Size(),
minio.PutObjectOptions{
ContentType: "image/jpeg",
},
)
if err != nil {
log.Errorf("Could not store image file: %s", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
func isSupportedFileType(file multipart.File) bool {
head := make([]byte, 20)
file.Read(head)
file.Seek(0, io.SeekStart)
kind, _ := filetype.Match(head)
return kind.MIME.Value == "image/jpeg" || kind.MIME.Value == "image/png" || kind.MIME.Value == "image/heif"
}