forked from imgproxy/imgproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
processing_options.go
1151 lines (928 loc) · 25.1 KB
/
processing_options.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"github.com/imgproxy/imgproxy/v2/structdiff"
)
type urlOption struct {
Name string
Args []string
}
type urlOptions []urlOption
type processingHeaders struct {
Accept string
Width string
ViewportWidth string
DPR string
}
type gravityType int
const (
gravityUnknown gravityType = iota
gravityCenter
gravityNorth
gravityEast
gravitySouth
gravityWest
gravityNorthWest
gravityNorthEast
gravitySouthWest
gravitySouthEast
gravitySmart
gravityFocusPoint
)
var gravityTypes = map[string]gravityType{
"ce": gravityCenter,
"no": gravityNorth,
"ea": gravityEast,
"so": gravitySouth,
"we": gravityWest,
"nowe": gravityNorthWest,
"noea": gravityNorthEast,
"sowe": gravitySouthWest,
"soea": gravitySouthEast,
"sm": gravitySmart,
"fp": gravityFocusPoint,
}
type resizeType int
const (
resizeFit resizeType = iota
resizeFill
resizeCrop
resizeAuto
)
var resizeTypes = map[string]resizeType{
"fit": resizeFit,
"fill": resizeFill,
"crop": resizeCrop,
"auto": resizeAuto,
}
type rgbColor struct{ R, G, B uint8 }
var hexColorRegex = regexp.MustCompile("^([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
const (
hexColorLongFormat = "%02x%02x%02x"
hexColorShortFormat = "%1x%1x%1x"
)
type gravityOptions struct {
Type gravityType
X, Y float64
}
type extendOptions struct {
Enabled bool
Gravity gravityOptions
}
type cropOptions struct {
Width int
Height int
Gravity gravityOptions
}
type paddingOptions struct {
Enabled bool
Top int
Right int
Bottom int
Left int
}
type trimOptions struct {
Enabled bool
Threshold float64
Smart bool
Color rgbColor
EqualHor bool
EqualVer bool
}
type watermarkOptions struct {
Enabled bool
Opacity float64
Replicate bool
Gravity gravityOptions
Scale float64
}
type processingOptions struct {
ResizingType resizeType
Width int
Height int
Dpr float64
Gravity gravityOptions
Enlarge bool
Extend extendOptions
Crop cropOptions
Padding paddingOptions
Trim trimOptions
Format imageType
Quality int
MaxBytes int
Flatten bool
Background rgbColor
Blur float32
Sharpen float32
StripMetadata bool
CacheBuster string
Watermark watermarkOptions
PreferWebP bool
EnforceWebP bool
Filename string
UsedPresets []string
}
const (
imageURLCtxKey = ctxKey("imageUrl")
processingOptionsCtxKey = ctxKey("processingOptions")
urlTokenPlain = "plain"
maxClientHintDPR = 8
msgForbidden = "Forbidden"
msgInvalidURL = "Invalid URL"
msgInvalidSource = "Invalid Source"
)
func (gt gravityType) String() string {
for k, v := range gravityTypes {
if v == gt {
return k
}
}
return ""
}
func (gt gravityType) MarshalJSON() ([]byte, error) {
for k, v := range gravityTypes {
if v == gt {
return []byte(fmt.Sprintf("%q", k)), nil
}
}
return []byte("null"), nil
}
func (rt resizeType) String() string {
for k, v := range resizeTypes {
if v == rt {
return k
}
}
return ""
}
func (rt resizeType) MarshalJSON() ([]byte, error) {
for k, v := range resizeTypes {
if v == rt {
return []byte(fmt.Sprintf("%q", k)), nil
}
}
return []byte("null"), nil
}
var (
_newProcessingOptions processingOptions
newProcessingOptionsOnce sync.Once
)
func newProcessingOptions() *processingOptions {
newProcessingOptionsOnce.Do(func() {
_newProcessingOptions = processingOptions{
ResizingType: resizeFit,
Width: 0,
Height: 0,
Gravity: gravityOptions{Type: gravityCenter},
Enlarge: false,
Extend: extendOptions{Enabled: false, Gravity: gravityOptions{Type: gravityCenter}},
Padding: paddingOptions{Enabled: false},
Trim: trimOptions{Enabled: false, Threshold: 10, Smart: true},
Quality: conf.Quality,
MaxBytes: 0,
Format: imageTypeUnknown,
Background: rgbColor{255, 255, 255},
Blur: 0,
Sharpen: 0,
Dpr: 1,
Watermark: watermarkOptions{Opacity: 1, Replicate: false, Gravity: gravityOptions{Type: gravityCenter}},
StripMetadata: conf.StripMetadata,
}
})
po := _newProcessingOptions
po.UsedPresets = make([]string, 0, len(conf.Presets))
return &po
}
func (po *processingOptions) isPresetUsed(name string) bool {
for _, usedName := range po.UsedPresets {
if usedName == name {
return true
}
}
return false
}
func (po *processingOptions) presetUsed(name string) {
po.UsedPresets = append(po.UsedPresets, name)
}
func (po *processingOptions) Diff() structdiff.Entries {
return structdiff.Diff(newProcessingOptions(), po)
}
func (po *processingOptions) String() string {
return po.Diff().String()
}
func (po *processingOptions) MarshalJSON() ([]byte, error) {
return po.Diff().MarshalJSON()
}
func colorFromHex(hexcolor string) (rgbColor, error) {
c := rgbColor{}
if !hexColorRegex.MatchString(hexcolor) {
return c, fmt.Errorf("Invalid hex color: %s", hexcolor)
}
if len(hexcolor) == 3 {
fmt.Sscanf(hexcolor, hexColorShortFormat, &c.R, &c.G, &c.B)
c.R *= 17
c.G *= 17
c.B *= 17
} else {
fmt.Sscanf(hexcolor, hexColorLongFormat, &c.R, &c.G, &c.B)
}
return c, nil
}
func decodeBase64URL(parts []string) (string, string, error) {
var format string
encoded := strings.Join(parts, "")
urlParts := strings.Split(encoded, ".")
if len(urlParts[0]) == 0 {
return "", "", errors.New("Image URL is empty")
}
if len(urlParts) > 2 {
return "", "", fmt.Errorf("Multiple formats are specified: %s", encoded)
}
if len(urlParts) == 2 && len(urlParts[1]) > 0 {
format = urlParts[1]
}
imageURL, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(urlParts[0], "="))
if err != nil {
return "", "", fmt.Errorf("Invalid url encoding: %s", encoded)
}
fullURL := fmt.Sprintf("%s%s", conf.BaseURL, string(imageURL))
return fullURL, format, nil
}
func decodePlainURL(parts []string) (string, string, error) {
var format string
encoded := strings.Join(parts, "/")
urlParts := strings.Split(encoded, "@")
if len(urlParts[0]) == 0 {
return "", "", errors.New("Image URL is empty")
}
if len(urlParts) > 2 {
return "", "", fmt.Errorf("Multiple formats are specified: %s", encoded)
}
if len(urlParts) == 2 && len(urlParts[1]) > 0 {
format = urlParts[1]
}
unescaped, err := url.PathUnescape(urlParts[0])
if err != nil {
return "", "", fmt.Errorf("Invalid url encoding: %s", encoded)
}
fullURL := fmt.Sprintf("%s%s", conf.BaseURL, unescaped)
return fullURL, format, nil
}
func decodeURL(parts []string) (string, string, error) {
if len(parts) == 0 {
return "", "", errors.New("Image URL is empty")
}
if parts[0] == urlTokenPlain && len(parts) > 1 {
return decodePlainURL(parts[1:])
}
return decodeBase64URL(parts)
}
func parseDimension(d *int, name, arg string) error {
if v, err := strconv.Atoi(arg); err == nil && v >= 0 {
*d = v
} else {
return fmt.Errorf("Invalid %s: %s", name, arg)
}
return nil
}
func parseBoolOption(str string) bool {
b, err := strconv.ParseBool(str)
if err != nil {
logWarning("`%s` is not a valid boolean value. Treated as false", str)
}
return b
}
func isGravityOffcetValid(gravity gravityType, offset float64) bool {
if gravity == gravityCenter {
return true
}
return offset >= 0 && (gravity != gravityFocusPoint || offset <= 1)
}
func parseGravity(g *gravityOptions, args []string) error {
nArgs := len(args)
if nArgs > 3 {
return fmt.Errorf("Invalid gravity arguments: %v", args)
}
if t, ok := gravityTypes[args[0]]; ok {
g.Type = t
} else {
return fmt.Errorf("Invalid gravity: %s", args[0])
}
if g.Type == gravitySmart && nArgs > 1 {
return fmt.Errorf("Invalid gravity arguments: %v", args)
} else if g.Type == gravityFocusPoint && nArgs != 3 {
return fmt.Errorf("Invalid gravity arguments: %v", args)
}
if nArgs > 1 {
if x, err := strconv.ParseFloat(args[1], 64); err == nil && isGravityOffcetValid(g.Type, x) {
g.X = x
} else {
return fmt.Errorf("Invalid gravity X: %s", args[1])
}
}
if nArgs > 2 {
if y, err := strconv.ParseFloat(args[2], 64); err == nil && isGravityOffcetValid(g.Type, y) {
g.Y = y
} else {
return fmt.Errorf("Invalid gravity Y: %s", args[2])
}
}
return nil
}
func applyWidthOption(po *processingOptions, args []string) error {
if len(args) > 1 {
return fmt.Errorf("Invalid width arguments: %v", args)
}
return parseDimension(&po.Width, "width", args[0])
}
func applyHeightOption(po *processingOptions, args []string) error {
if len(args) > 1 {
return fmt.Errorf("Invalid height arguments: %v", args)
}
return parseDimension(&po.Height, "height", args[0])
}
func applyEnlargeOption(po *processingOptions, args []string) error {
if len(args) > 1 {
return fmt.Errorf("Invalid enlarge arguments: %v", args)
}
po.Enlarge = parseBoolOption(args[0])
return nil
}
func applyExtendOption(po *processingOptions, args []string) error {
if len(args) > 4 {
return fmt.Errorf("Invalid extend arguments: %v", args)
}
po.Extend.Enabled = parseBoolOption(args[0])
if len(args) > 1 {
if err := parseGravity(&po.Extend.Gravity, args[1:]); err != nil {
return err
}
if po.Extend.Gravity.Type == gravitySmart {
return errors.New("extend doesn't support smart gravity")
}
}
return nil
}
func applySizeOption(po *processingOptions, args []string) (err error) {
if len(args) > 7 {
return fmt.Errorf("Invalid size arguments: %v", args)
}
if len(args) >= 1 && len(args[0]) > 0 {
if err = applyWidthOption(po, args[0:1]); err != nil {
return
}
}
if len(args) >= 2 && len(args[1]) > 0 {
if err = applyHeightOption(po, args[1:2]); err != nil {
return
}
}
if len(args) >= 3 && len(args[2]) > 0 {
if err = applyEnlargeOption(po, args[2:3]); err != nil {
return
}
}
if len(args) >= 4 && len(args[3]) > 0 {
if err = applyExtendOption(po, args[3:]); err != nil {
return
}
}
return nil
}
func applyResizingTypeOption(po *processingOptions, args []string) error {
if len(args) > 1 {
return fmt.Errorf("Invalid resizing type arguments: %v", args)
}
if r, ok := resizeTypes[args[0]]; ok {
po.ResizingType = r
} else {
return fmt.Errorf("Invalid resize type: %s", args[0])
}
return nil
}
func applyResizeOption(po *processingOptions, args []string) error {
if len(args) > 8 {
return fmt.Errorf("Invalid resize arguments: %v", args)
}
if len(args[0]) > 0 {
if err := applyResizingTypeOption(po, args[0:1]); err != nil {
return err
}
}
if len(args) > 1 {
if err := applySizeOption(po, args[1:]); err != nil {
return err
}
}
return nil
}
func applyDprOption(po *processingOptions, args []string) error {
if len(args) > 1 {
return fmt.Errorf("Invalid dpr arguments: %v", args)
}
if d, err := strconv.ParseFloat(args[0], 64); err == nil && d > 0 {
po.Dpr = d
} else {
return fmt.Errorf("Invalid dpr: %s", args[0])
}
return nil
}
func applyGravityOption(po *processingOptions, args []string) error {
return parseGravity(&po.Gravity, args)
}
func applyCropOption(po *processingOptions, args []string) error {
if len(args) > 5 {
return fmt.Errorf("Invalid crop arguments: %v", args)
}
if err := parseDimension(&po.Crop.Width, "crop width", args[0]); err != nil {
return err
}
if len(args) > 1 {
if err := parseDimension(&po.Crop.Height, "crop height", args[1]); err != nil {
return err
}
}
if len(args) > 2 {
return parseGravity(&po.Crop.Gravity, args[2:])
}
return nil
}
func applyPaddingOption(po *processingOptions, args []string) error {
nArgs := len(args)
if nArgs < 1 || nArgs > 4 {
return fmt.Errorf("Invalid padding arguments: %v", args)
}
po.Padding.Enabled = true
if nArgs > 0 && len(args[0]) > 0 {
if err := parseDimension(&po.Padding.Top, "padding top (+all)", args[0]); err != nil {
return err
}
po.Padding.Right = po.Padding.Top
po.Padding.Bottom = po.Padding.Top
po.Padding.Left = po.Padding.Top
}
if nArgs > 1 && len(args[1]) > 0 {
if err := parseDimension(&po.Padding.Right, "padding right (+left)", args[1]); err != nil {
return err
}
po.Padding.Left = po.Padding.Right
}
if nArgs > 2 && len(args[2]) > 0 {
if err := parseDimension(&po.Padding.Bottom, "padding bottom", args[2]); err != nil {
return err
}
}
if nArgs > 3 && len(args[3]) > 0 {
if err := parseDimension(&po.Padding.Left, "padding left", args[3]); err != nil {
return err
}
}
if po.Padding.Top == 0 && po.Padding.Right == 0 && po.Padding.Bottom == 0 && po.Padding.Left == 0 {
po.Padding.Enabled = false
}
return nil
}
func applyTrimOption(po *processingOptions, args []string) error {
nArgs := len(args)
if nArgs > 4 {
return fmt.Errorf("Invalid trim arguments: %v", args)
}
if t, err := strconv.ParseFloat(args[0], 64); err == nil && t >= 0 {
po.Trim.Enabled = true
po.Trim.Threshold = t
} else {
return fmt.Errorf("Invalid trim threshold: %s", args[0])
}
if nArgs > 1 && len(args[1]) > 0 {
if c, err := colorFromHex(args[1]); err == nil {
po.Trim.Color = c
po.Trim.Smart = false
} else {
return fmt.Errorf("Invalid trim color: %s", args[1])
}
}
if nArgs > 2 && len(args[2]) > 0 {
po.Trim.EqualHor = parseBoolOption(args[2])
}
if nArgs > 3 && len(args[3]) > 0 {
po.Trim.EqualVer = parseBoolOption(args[3])
}
return nil
}
func applyQualityOption(po *processingOptions, args []string) error {
if len(args) > 1 {
return fmt.Errorf("Invalid quality arguments: %v", args)
}
if q, err := strconv.Atoi(args[0]); err == nil && q > 0 && q <= 100 {
po.Quality = q
} else {
return fmt.Errorf("Invalid quality: %s", args[0])
}
return nil
}
func applyMaxBytesOption(po *processingOptions, args []string) error {
if len(args) > 1 {
return fmt.Errorf("Invalid max_bytes arguments: %v", args)
}
if max, err := strconv.Atoi(args[0]); err == nil && max >= 0 {
po.MaxBytes = max
} else {
return fmt.Errorf("Invalid max_bytes: %s", args[0])
}
return nil
}
func applyBackgroundOption(po *processingOptions, args []string) error {
switch len(args) {
case 1:
if len(args[0]) == 0 {
po.Flatten = false
} else if c, err := colorFromHex(args[0]); err == nil {
po.Flatten = true
po.Background = c
} else {
return fmt.Errorf("Invalid background argument: %s", err)
}
case 3:
po.Flatten = true
if r, err := strconv.ParseUint(args[0], 10, 8); err == nil && r <= 255 {
po.Background.R = uint8(r)
} else {
return fmt.Errorf("Invalid background red channel: %s", args[0])
}
if g, err := strconv.ParseUint(args[1], 10, 8); err == nil && g <= 255 {
po.Background.G = uint8(g)
} else {
return fmt.Errorf("Invalid background green channel: %s", args[1])
}
if b, err := strconv.ParseUint(args[2], 10, 8); err == nil && b <= 255 {
po.Background.B = uint8(b)
} else {
return fmt.Errorf("Invalid background blue channel: %s", args[2])
}
default:
return fmt.Errorf("Invalid background arguments: %v", args)
}
return nil
}
func applyBlurOption(po *processingOptions, args []string) error {
if len(args) > 1 {
return fmt.Errorf("Invalid blur arguments: %v", args)
}
if b, err := strconv.ParseFloat(args[0], 32); err == nil && b >= 0 {
po.Blur = float32(b)
} else {
return fmt.Errorf("Invalid blur: %s", args[0])
}
return nil
}
func applySharpenOption(po *processingOptions, args []string) error {
if len(args) > 1 {
return fmt.Errorf("Invalid sharpen arguments: %v", args)
}
if s, err := strconv.ParseFloat(args[0], 32); err == nil && s >= 0 {
po.Sharpen = float32(s)
} else {
return fmt.Errorf("Invalid sharpen: %s", args[0])
}
return nil
}
func applyPresetOption(po *processingOptions, args []string) error {
for _, preset := range args {
if p, ok := conf.Presets[preset]; ok {
if po.isPresetUsed(preset) {
logWarning("Recursive preset usage is detected: %s", preset)
continue
}
po.presetUsed(preset)
if err := applyProcessingOptions(po, p); err != nil {
return err
}
} else {
return fmt.Errorf("Unknown preset: %s", preset)
}
}
return nil
}
func applyWatermarkOption(po *processingOptions, args []string) error {
if len(args) > 7 {
return fmt.Errorf("Invalid watermark arguments: %v", args)
}
if o, err := strconv.ParseFloat(args[0], 64); err == nil && o >= 0 && o <= 1 {
po.Watermark.Enabled = o > 0
po.Watermark.Opacity = o
} else {
return fmt.Errorf("Invalid watermark opacity: %s", args[0])
}
if len(args) > 1 && len(args[1]) > 0 {
if args[1] == "re" {
po.Watermark.Replicate = true
} else if g, ok := gravityTypes[args[1]]; ok && g != gravityFocusPoint && g != gravitySmart {
po.Watermark.Gravity.Type = g
} else {
return fmt.Errorf("Invalid watermark position: %s", args[1])
}
}
if len(args) > 2 && len(args[2]) > 0 {
if x, err := strconv.Atoi(args[2]); err == nil {
po.Watermark.Gravity.X = float64(x)
} else {
return fmt.Errorf("Invalid watermark X offset: %s", args[2])
}
}
if len(args) > 3 && len(args[3]) > 0 {
if y, err := strconv.Atoi(args[3]); err == nil {
po.Watermark.Gravity.Y = float64(y)
} else {
return fmt.Errorf("Invalid watermark Y offset: %s", args[3])
}
}
if len(args) > 4 && len(args[4]) > 0 {
if s, err := strconv.ParseFloat(args[4], 64); err == nil && s >= 0 {
po.Watermark.Scale = s
} else {
return fmt.Errorf("Invalid watermark scale: %s", args[4])
}
}
return nil
}
func applyFormatOption(po *processingOptions, args []string) error {
if len(args) > 1 {
return fmt.Errorf("Invalid format arguments: %v", args)
}
if f, ok := imageTypes[args[0]]; ok {
po.Format = f
} else {
return fmt.Errorf("Invalid image format: %s", args[0])
}
if !imageTypeSaveSupport(po.Format) {
return fmt.Errorf("Resulting image format is not supported: %s", po.Format)
}
return nil
}
func applyCacheBusterOption(po *processingOptions, args []string) error {
if len(args) > 1 {
return fmt.Errorf("Invalid cache buster arguments: %v", args)
}
po.CacheBuster = args[0]
return nil
}
func applyFilenameOption(po *processingOptions, args []string) error {
if len(args) > 1 {
return fmt.Errorf("Invalid filename arguments: %v", args)
}
po.Filename = args[0]
return nil
}
func applyStripMetadataOption(po *processingOptions, args []string) error {
if len(args[0]) > 0 {
po.StripMetadata = parseBoolOption(args[0])
}
return nil
}
func applyProcessingOption(po *processingOptions, name string, args []string) error {
switch name {
case "format", "f", "ext":
return applyFormatOption(po, args)
case "resize", "rs":
return applyResizeOption(po, args)
case "resizing_type", "rt":
return applyResizingTypeOption(po, args)
case "size", "s":
return applySizeOption(po, args)
case "width", "w":
return applyWidthOption(po, args)
case "height", "h":
return applyHeightOption(po, args)
case "enlarge", "el":
return applyEnlargeOption(po, args)
case "extend", "ex":
return applyExtendOption(po, args)
case "dpr":
return applyDprOption(po, args)
case "gravity", "g":
return applyGravityOption(po, args)
case "crop", "c":
return applyCropOption(po, args)
case "trim", "t":
return applyTrimOption(po, args)
case "padding", "pd":
return applyPaddingOption(po, args)
case "quality", "q":
return applyQualityOption(po, args)
case "max_bytes", "mb":
return applyMaxBytesOption(po, args)
case "background", "bg":
return applyBackgroundOption(po, args)
case "blur", "bl":
return applyBlurOption(po, args)
case "sharpen", "sh":
return applySharpenOption(po, args)
case "watermark", "wm":
return applyWatermarkOption(po, args)
case "preset", "pr":
return applyPresetOption(po, args)
case "cachebuster", "cb":
return applyCacheBusterOption(po, args)
case "strip_metadata", "sm":
return applyStripMetadataOption(po, args)
case "filename", "fn":
return applyFilenameOption(po, args)
}
return fmt.Errorf("Unknown processing option: %s", name)
}
func applyProcessingOptions(po *processingOptions, options urlOptions) error {
for _, opt := range options {
if err := applyProcessingOption(po, opt.Name, opt.Args); err != nil {
return err
}
}
return nil
}
func isAllowedSource(imageURL string) bool {
if len(conf.AllowedSources) == 0 {
return true
}
for _, val := range conf.AllowedSources {
if strings.HasPrefix(imageURL, string(val)) {
return true
}
}
return false
}
func parseURLOptions(opts []string) (urlOptions, []string) {
parsed := make(urlOptions, 0, len(opts))
urlStart := len(opts) + 1
for i, opt := range opts {
args := strings.Split(opt, ":")
if len(args) == 1 {
urlStart = i
break
}
parsed = append(parsed, urlOption{Name: args[0], Args: args[1:]})
}
var rest []string
if urlStart < len(opts) {
rest = opts[urlStart:]
} else {
rest = []string{}
}
return parsed, rest
}
func defaultProcessingOptions(headers *processingHeaders) (*processingOptions, error) {
po := newProcessingOptions()
if strings.Contains(headers.Accept, "image/webp") {
po.PreferWebP = conf.EnableWebpDetection || conf.EnforceWebp
po.EnforceWebP = conf.EnforceWebp
}
if conf.EnableClientHints && len(headers.ViewportWidth) > 0 {
if vw, err := strconv.Atoi(headers.ViewportWidth); err == nil {
po.Width = vw
}
}
if conf.EnableClientHints && len(headers.Width) > 0 {
if w, err := strconv.Atoi(headers.Width); err == nil {
po.Width = w
}
}
if conf.EnableClientHints && len(headers.DPR) > 0 {
if dpr, err := strconv.ParseFloat(headers.DPR, 64); err == nil && (dpr > 0 && dpr <= maxClientHintDPR) {
po.Dpr = dpr
}
}
if _, ok := conf.Presets["default"]; ok {
if err := applyPresetOption(po, []string{"default"}); err != nil {
return po, err
}
}
return po, nil
}
func parsePathAdvanced(parts []string, headers *processingHeaders) (string, *processingOptions, error) {
po, err := defaultProcessingOptions(headers)
if err != nil {
return "", po, err
}
options, urlParts := parseURLOptions(parts)