This repository has been archived by the owner on Nov 28, 2023. It is now read-only.
/
web.go
356 lines (280 loc) · 8.68 KB
/
web.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package welcomerimages
import (
"bytes"
"encoding/base64"
"encoding/json"
"io/ioutil"
"math"
"mime"
"net/http"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/WelcomerTeam/WelcomerImages/pkg/methodrouter"
"github.com/boltdb/bolt"
"github.com/gorilla/mux"
"github.com/kalafut/imohash"
"github.com/rs/zerolog"
gotils "github.com/savsgio/gotils/strconv"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpadaptor"
)
// HandleRequest handles the HTTP requests.
func (wi *WelcomerImageService) HandleRequest(ctx *fasthttp.RequestCtx) {
var processingMS int64
start := time.Now().UTC()
path := gotils.B2S(ctx.Path())
defer func() {
var zlog *zerolog.Event
statusCode := ctx.Response.StatusCode()
switch {
case (statusCode >= 400 && statusCode <= 499):
zlog = wi.Logger.Warn()
case (statusCode >= 500 && statusCode <= 599):
zlog = wi.Logger.Error()
default:
zlog = wi.Logger.Info()
}
zlog.Msgf("%s %s %s %d %d %dms",
ctx.RemoteAddr(),
ctx.Request.Header.Method(),
ctx.Request.URI().PathOriginal(),
statusCode,
len(ctx.Response.Body()),
processingMS,
)
cdnResponseCode.WithLabelValues(
gotils.B2S(ctx.Request.Header.Method()),
strconv.Itoa(statusCode),
).Add(1)
cdnResponseTimes.Observe(float64(processingMS) / msTos)
}()
fasthttp.CompressHandlerBrotliLevel(func(ctx *fasthttp.RequestCtx) {
fasthttpadaptor.NewFastHTTPHandler(wi.Router)(ctx)
if path == "/" {
ctx.Response.Header.Set("Content-Type", "text/html")
ctx.SendFile(wi.Configuration.Store.IndexLocation)
return
}
// If there is no URL in router then try serving from the dist
// folder.
if ctx.Response.StatusCode() == http.StatusNotFound &&
path != "/" && wi.Configuration.Store.StaticPath != "" {
ctx.Response.Reset()
wi.distHandler(ctx)
}
}, fasthttp.CompressBrotliDefaultCompression, fasthttp.CompressDefaultCompression)(ctx)
processingMS = int64(math.Max(float64(time.Since(start).Round(time.Millisecond).Milliseconds()), 1))
ctx.Response.Header.Set("X-Elapsed", strconv.FormatInt(processingMS, 10))
}
// GET /images/{guid}
// Retrieves an image based off of its guid. This does not require Authorization.
// Input headers:
// Output headers:
// ImagesGet handles retrieving images.
func ImagesGet(wi *WelcomerImageService) http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
var err error
vars := mux.Vars(r)
guid, ok := vars["guid"]
if !ok {
resp := ImageCreateResponse{
Success: false,
Message: "Missing 'guid' argument",
}
res, err := json.Marshal(resp)
if err != nil {
wi.Logger.Error().Err(err).Msg("Caught exception marshalling response")
}
rw.WriteHeader(http.StatusBadRequest)
rw.Write(res)
return
}
var d ImageData
var v []byte
// removes .png, .gif etc.
guid = guid[0 : len(guid)-len(filepath.Ext(guid))]
wi.Database.View(func(tx *bolt.Tx) error {
v = tx.Bucket(bucketName).Get(gotils.S2B(guid))
return nil
})
if v != nil {
err = json.Unmarshal(v, &d)
if err != nil {
wi.Logger.Error().Err(err).Str("key", guid).Msg("Invalid data received from Bolt")
d = wi.DefaultImage
}
d.Path = path.Join(wi.Configuration.Store.StorePath, d.Path)
} else {
d = wi.DefaultImage
}
if !d.isDefault && fsExists(d.Path) {
f, err := ioutil.ReadFile(d.Path)
if err == nil {
rw.Header().Set("Content-Type", mime.TypeByExtension(filepath.Ext(d.Path)))
rw.WriteHeader(http.StatusOK)
rw.Write(f)
return
} else {
wi.Logger.Error().Err(err).Msg("Failed to read file")
}
}
rw.Header().Set("Content-Type", "image/png") // TODO: FIX
rw.WriteHeader(http.StatusOK)
rw.Write(wi.DefaultImageContent)
}
}
// GET /images/{guid}
// Creates a new image and returns either a hotlink or the image.
// This does not require Authorization if AllowAnonymousAccess is enabled
// else the Authorization header must match an APIKey in the configuration.
// Input headers:
// Authorization: APIKey
// Body: Refer to ImageCreateArguments structure
// Output headers:
// X-Gen-Elapsed: Time taken to generate image
// ImagesCreate handles creating images.
func ImagesCreate(wi *WelcomerImageService) http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
// Ensures we finish any active ImagesCreate requests
// before closing down.
wi.PoolWaiter.Add(1)
defer wi.PoolWaiter.Done()
var rd ImageCreateArguments
err := json.NewDecoder(r.Body).Decode(&rd)
if err != nil {
wi.Logger.Error().Err(err).
Msg("Failed to parse json request")
resp := ImageCreateResponse{
Success: false,
Message: err.Error(),
}
res, err := json.Marshal(resp)
if err != nil {
wi.Logger.Error().Err(err).Msg("Caught exception marshalling response")
}
rw.WriteHeader(http.StatusBadRequest)
rw.Write(res)
return
}
// Images are sent in ARGB format and have to be parsed manually
rd.Options.BorderColour = convertARGB(rd.Options.BorderColourHex, colorWhite)
rd.Options.ProfileBorderColour = convertARGB(rd.Options.ProfileBorderColourHex, colorWhite)
rd.Options.TextColour = convertARGB(rd.Options.TextColourHex, colorWhite)
rd.Options.TextStrokeColour = convertARGB(rd.Options.TextStrokeColourHex, colorBlack)
apiKey := r.Header.Get("Authorization")
if !wi.Configuration.Store.AllowAnonymousAccess {
for _, v := range wi.Configuration.APIKeys {
if v == apiKey {
goto postAuth
}
}
rw.WriteHeader(http.StatusUnauthorized)
return
}
postAuth:
var b bytes.Buffer
start := time.Now().UTC()
ext, err := wi.GenerateImage(&b, rd.Options)
now := time.Now().UTC()
ms := now.Sub(start).Round(time.Millisecond).Milliseconds()
rw.Header().Set("X-Gen-Elapsed", strconv.FormatInt(ms, 10))
if err != nil {
wi.Logger.Error().Err(err).
Msg("Failed to generate image")
resp := ImageCreateResponse{
Success: false,
Message: err.Error(),
}
res, err := json.Marshal(resp)
if err != nil {
wi.Logger.Error().Err(err).Msg("Caught exception marshalling response")
}
rw.WriteHeader(http.StatusInternalServerError)
rw.Write(res)
return
}
imagesProcessed.Inc()
imagesProcessTime.Observe(float64(ms) / msTos)
imagesTotalSize.Add(float64(b.Len()))
u := imohash.New()
by := u.Sum(b.Bytes())
k := strings.TrimRight(base64.URLEncoding.EncodeToString(by[:]), "=")
storeName := k + "." + ext
storePath := path.Join(wi.Configuration.Store.StorePath, storeName)
storeImage := rd.ForceCache || b.Len() >= rd.FilesizeLimit
wi.Logger.Info().
Bool("store", storeImage).
Str("path", storePath).
Int64("ms", ms).
Msg("Generated image")
if !storeImage {
rw.WriteHeader(http.StatusOK)
_, err = b.WriteTo(rw)
if err != nil {
wi.Logger.Error().Err(err).Msg("Failed to write image to body")
}
return
}
err = ioutil.WriteFile(storePath, b.Bytes(), 0o644)
if err != nil {
wi.Logger.Error().Err(err).
Str("path", storePath).
Msg("Failed to write file")
rw.WriteHeader(http.StatusInternalServerError)
return
}
wi.Logger.Debug().
Str("path", storePath).
Msg("Successfully written file")
d := ImageData{
ID: k,
GuildID: rd.Options.GuildId,
Size: b.Len(),
Path: storeName,
CreatedAt: now,
ExpiresAt: now.Add(imageTTL),
}
v, err := json.Marshal(d)
if err != nil {
wi.Logger.Error().Err(err).Msg("Caught exception marshaling ImageData")
}
err = wi.Database.Update(func(tx *bolt.Tx) error {
return tx.Bucket(bucketName).Put(gotils.S2B(k), v)
})
if err != nil {
wi.Logger.Error().Err(err).Msg("Caught exception inserting into Bolt")
}
resp := ImageCreateResponse{
Success: true,
Bookmarkable: wi.Configuration.HTTP.BookmarkableURL + "/images/" + d.ID + "." + ext,
ImageData: &d,
}
res, err := json.Marshal(resp)
if err != nil {
wi.Logger.Error().Err(err).Msg("Caught exception marshalling response")
}
rw.WriteHeader(http.StatusOK)
rw.Write(res)
}
}
type ImageCreateArguments struct {
// cache = force_cache or filesize >= filesize_limit
ForceCache bool `json:"force_cache"`
FilesizeLimit int `json:"filesize_limit"`
Options ImageOpts `json:"options"`
}
type ImageCreateResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
Bookmarkable string `json:"bookmarkable,omitempty"`
ImageData *ImageData `json:"image_data,omitempty"`
}
func createEndpoints(wi *WelcomerImageService) *methodrouter.MethodRouter {
router := methodrouter.NewMethodRouter()
router.HandleFunc("/images/{guid}", ImagesGet(wi), "GET") // Retrieves image
router.HandleFunc("/images", ImagesCreate(wi), "POST") // Creates image
return router
}