processing_options.go 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  1. package options
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "time"
  9. log "github.com/sirupsen/logrus"
  10. "github.com/imgproxy/imgproxy/v3/config"
  11. "github.com/imgproxy/imgproxy/v3/ierrors"
  12. "github.com/imgproxy/imgproxy/v3/imagetype"
  13. "github.com/imgproxy/imgproxy/v3/imath"
  14. "github.com/imgproxy/imgproxy/v3/structdiff"
  15. "github.com/imgproxy/imgproxy/v3/vips"
  16. )
  17. const maxClientHintDPR = 8
  18. var errExpiredURL = errors.New("Expired URL")
  19. type ExtendOptions struct {
  20. Enabled bool
  21. Gravity GravityOptions
  22. }
  23. type CropOptions struct {
  24. Width float64
  25. Height float64
  26. Gravity GravityOptions
  27. }
  28. type PaddingOptions struct {
  29. Enabled bool
  30. Top int
  31. Right int
  32. Bottom int
  33. Left int
  34. }
  35. type TrimOptions struct {
  36. Enabled bool
  37. Threshold float64
  38. Smart bool
  39. Color vips.Color
  40. EqualHor bool
  41. EqualVer bool
  42. }
  43. type WatermarkOptions struct {
  44. Enabled bool
  45. Opacity float64
  46. Replicate bool
  47. Gravity GravityOptions
  48. Scale float64
  49. }
  50. type ProcessingOptions struct {
  51. ResizingType ResizeType
  52. Width int
  53. Height int
  54. MinWidth int
  55. MinHeight int
  56. ZoomWidth float64
  57. ZoomHeight float64
  58. Dpr float64
  59. Gravity GravityOptions
  60. Enlarge bool
  61. Extend ExtendOptions
  62. Crop CropOptions
  63. Padding PaddingOptions
  64. Trim TrimOptions
  65. Rotate int
  66. Format imagetype.Type
  67. Quality int
  68. FormatQuality map[imagetype.Type]int
  69. MaxBytes int
  70. Flatten bool
  71. Background vips.Color
  72. Blur float32
  73. Sharpen float32
  74. Pixelate int
  75. StripMetadata bool
  76. KeepCopyright bool
  77. StripColorProfile bool
  78. AutoRotate bool
  79. EnforceThumbnail bool
  80. ReturnAttachment bool
  81. SkipProcessingFormats []imagetype.Type
  82. CacheBuster string
  83. Watermark WatermarkOptions
  84. PreferWebP bool
  85. EnforceWebP bool
  86. PreferAvif bool
  87. EnforceAvif bool
  88. Filename string
  89. UsedPresets []string
  90. defaultQuality int
  91. }
  92. func NewProcessingOptions() *ProcessingOptions {
  93. po := ProcessingOptions{
  94. ResizingType: ResizeFit,
  95. Width: 0,
  96. Height: 0,
  97. ZoomWidth: 1,
  98. ZoomHeight: 1,
  99. Gravity: GravityOptions{Type: GravityCenter},
  100. Enlarge: false,
  101. Extend: ExtendOptions{Enabled: false, Gravity: GravityOptions{Type: GravityCenter}},
  102. Padding: PaddingOptions{Enabled: false},
  103. Trim: TrimOptions{Enabled: false, Threshold: 10, Smart: true},
  104. Rotate: 0,
  105. Quality: 0,
  106. MaxBytes: 0,
  107. Format: imagetype.Unknown,
  108. Background: vips.Color{R: 255, G: 255, B: 255},
  109. Blur: 0,
  110. Sharpen: 0,
  111. Dpr: 1,
  112. Watermark: WatermarkOptions{Opacity: 1, Replicate: false, Gravity: GravityOptions{Type: GravityCenter}},
  113. StripMetadata: config.StripMetadata,
  114. KeepCopyright: config.KeepCopyright,
  115. StripColorProfile: config.StripColorProfile,
  116. AutoRotate: config.AutoRotate,
  117. EnforceThumbnail: config.EnforceThumbnail,
  118. ReturnAttachment: config.ReturnAttachment,
  119. SkipProcessingFormats: append([]imagetype.Type(nil), config.SkipProcessingFormats...),
  120. UsedPresets: make([]string, 0, len(config.Presets)),
  121. // Basically, we need this to update ETag when `IMGPROXY_QUALITY` is changed
  122. defaultQuality: config.Quality,
  123. }
  124. po.FormatQuality = make(map[imagetype.Type]int, len(config.FormatQuality))
  125. for k, v := range config.FormatQuality {
  126. po.FormatQuality[k] = v
  127. }
  128. return &po
  129. }
  130. func (po *ProcessingOptions) GetQuality() int {
  131. q := po.Quality
  132. if q == 0 {
  133. q = po.FormatQuality[po.Format]
  134. }
  135. if q == 0 {
  136. q = po.defaultQuality
  137. }
  138. return q
  139. }
  140. func (po *ProcessingOptions) isPresetUsed(name string) bool {
  141. for _, usedName := range po.UsedPresets {
  142. if usedName == name {
  143. return true
  144. }
  145. }
  146. return false
  147. }
  148. func (po *ProcessingOptions) Diff() structdiff.Entries {
  149. return structdiff.Diff(NewProcessingOptions(), po)
  150. }
  151. func (po *ProcessingOptions) String() string {
  152. return po.Diff().String()
  153. }
  154. func (po *ProcessingOptions) MarshalJSON() ([]byte, error) {
  155. return po.Diff().MarshalJSON()
  156. }
  157. func parseDimension(d *int, name, arg string) error {
  158. if v, err := strconv.Atoi(arg); err == nil && v >= 0 {
  159. *d = v
  160. } else {
  161. return fmt.Errorf("Invalid %s: %s", name, arg)
  162. }
  163. return nil
  164. }
  165. func parseBoolOption(str string) bool {
  166. b, err := strconv.ParseBool(str)
  167. if err != nil {
  168. log.Warningf("`%s` is not a valid boolean value. Treated as false", str)
  169. }
  170. return b
  171. }
  172. func isGravityOffcetValid(gravity GravityType, offset float64) bool {
  173. return gravity != GravityFocusPoint || (offset >= 0 && offset <= 1)
  174. }
  175. func parseGravity(g *GravityOptions, args []string) error {
  176. nArgs := len(args)
  177. if nArgs > 3 {
  178. return fmt.Errorf("Invalid gravity arguments: %v", args)
  179. }
  180. if t, ok := gravityTypes[args[0]]; ok {
  181. g.Type = t
  182. } else {
  183. return fmt.Errorf("Invalid gravity: %s", args[0])
  184. }
  185. if g.Type == GravitySmart && nArgs > 1 {
  186. return fmt.Errorf("Invalid gravity arguments: %v", args)
  187. } else if g.Type == GravityFocusPoint && nArgs != 3 {
  188. return fmt.Errorf("Invalid gravity arguments: %v", args)
  189. }
  190. if nArgs > 1 {
  191. if x, err := strconv.ParseFloat(args[1], 64); err == nil && isGravityOffcetValid(g.Type, x) {
  192. g.X = x
  193. } else {
  194. return fmt.Errorf("Invalid gravity X: %s", args[1])
  195. }
  196. }
  197. if nArgs > 2 {
  198. if y, err := strconv.ParseFloat(args[2], 64); err == nil && isGravityOffcetValid(g.Type, y) {
  199. g.Y = y
  200. } else {
  201. return fmt.Errorf("Invalid gravity Y: %s", args[2])
  202. }
  203. }
  204. return nil
  205. }
  206. func applyWidthOption(po *ProcessingOptions, args []string) error {
  207. if len(args) > 1 {
  208. return fmt.Errorf("Invalid width arguments: %v", args)
  209. }
  210. return parseDimension(&po.Width, "width", args[0])
  211. }
  212. func applyHeightOption(po *ProcessingOptions, args []string) error {
  213. if len(args) > 1 {
  214. return fmt.Errorf("Invalid height arguments: %v", args)
  215. }
  216. return parseDimension(&po.Height, "height", args[0])
  217. }
  218. func applyMinWidthOption(po *ProcessingOptions, args []string) error {
  219. if len(args) > 1 {
  220. return fmt.Errorf("Invalid min width arguments: %v", args)
  221. }
  222. return parseDimension(&po.MinWidth, "min width", args[0])
  223. }
  224. func applyMinHeightOption(po *ProcessingOptions, args []string) error {
  225. if len(args) > 1 {
  226. return fmt.Errorf("Invalid min height arguments: %v", args)
  227. }
  228. return parseDimension(&po.MinHeight, " min height", args[0])
  229. }
  230. func applyEnlargeOption(po *ProcessingOptions, args []string) error {
  231. if len(args) > 1 {
  232. return fmt.Errorf("Invalid enlarge arguments: %v", args)
  233. }
  234. po.Enlarge = parseBoolOption(args[0])
  235. return nil
  236. }
  237. func applyExtendOption(po *ProcessingOptions, args []string) error {
  238. if len(args) > 4 {
  239. return fmt.Errorf("Invalid extend arguments: %v", args)
  240. }
  241. po.Extend.Enabled = parseBoolOption(args[0])
  242. if len(args) > 1 {
  243. if err := parseGravity(&po.Extend.Gravity, args[1:]); err != nil {
  244. return err
  245. }
  246. if po.Extend.Gravity.Type == GravitySmart {
  247. return errors.New("extend doesn't support smart gravity")
  248. }
  249. }
  250. return nil
  251. }
  252. func applySizeOption(po *ProcessingOptions, args []string) (err error) {
  253. if len(args) > 7 {
  254. return fmt.Errorf("Invalid size arguments: %v", args)
  255. }
  256. if len(args) >= 1 && len(args[0]) > 0 {
  257. if err = applyWidthOption(po, args[0:1]); err != nil {
  258. return
  259. }
  260. }
  261. if len(args) >= 2 && len(args[1]) > 0 {
  262. if err = applyHeightOption(po, args[1:2]); err != nil {
  263. return
  264. }
  265. }
  266. if len(args) >= 3 && len(args[2]) > 0 {
  267. if err = applyEnlargeOption(po, args[2:3]); err != nil {
  268. return
  269. }
  270. }
  271. if len(args) >= 4 && len(args[3]) > 0 {
  272. if err = applyExtendOption(po, args[3:]); err != nil {
  273. return
  274. }
  275. }
  276. return nil
  277. }
  278. func applyResizingTypeOption(po *ProcessingOptions, args []string) error {
  279. if len(args) > 1 {
  280. return fmt.Errorf("Invalid resizing type arguments: %v", args)
  281. }
  282. if r, ok := resizeTypes[args[0]]; ok {
  283. po.ResizingType = r
  284. } else {
  285. return fmt.Errorf("Invalid resize type: %s", args[0])
  286. }
  287. return nil
  288. }
  289. func applyResizeOption(po *ProcessingOptions, args []string) error {
  290. if len(args) > 8 {
  291. return fmt.Errorf("Invalid resize arguments: %v", args)
  292. }
  293. if len(args[0]) > 0 {
  294. if err := applyResizingTypeOption(po, args[0:1]); err != nil {
  295. return err
  296. }
  297. }
  298. if len(args) > 1 {
  299. if err := applySizeOption(po, args[1:]); err != nil {
  300. return err
  301. }
  302. }
  303. return nil
  304. }
  305. func applyZoomOption(po *ProcessingOptions, args []string) error {
  306. nArgs := len(args)
  307. if nArgs > 2 {
  308. return fmt.Errorf("Invalid zoom arguments: %v", args)
  309. }
  310. if z, err := strconv.ParseFloat(args[0], 64); err == nil && z > 0 {
  311. po.ZoomWidth = z
  312. po.ZoomHeight = z
  313. } else {
  314. return fmt.Errorf("Invalid zoom value: %s", args[0])
  315. }
  316. if nArgs > 1 {
  317. if z, err := strconv.ParseFloat(args[1], 64); err == nil && z > 0 {
  318. po.ZoomHeight = z
  319. } else {
  320. return fmt.Errorf("Invalid zoom value: %s", args[0])
  321. }
  322. }
  323. return nil
  324. }
  325. func applyDprOption(po *ProcessingOptions, args []string) error {
  326. if len(args) > 1 {
  327. return fmt.Errorf("Invalid dpr arguments: %v", args)
  328. }
  329. if d, err := strconv.ParseFloat(args[0], 64); err == nil && d > 0 {
  330. po.Dpr = d
  331. } else {
  332. return fmt.Errorf("Invalid dpr: %s", args[0])
  333. }
  334. return nil
  335. }
  336. func applyGravityOption(po *ProcessingOptions, args []string) error {
  337. return parseGravity(&po.Gravity, args)
  338. }
  339. func applyCropOption(po *ProcessingOptions, args []string) error {
  340. if len(args) > 5 {
  341. return fmt.Errorf("Invalid crop arguments: %v", args)
  342. }
  343. if w, err := strconv.ParseFloat(args[0], 64); err == nil && w >= 0 {
  344. po.Crop.Width = w
  345. } else {
  346. return fmt.Errorf("Invalid crop width: %s", args[0])
  347. }
  348. if len(args) > 1 {
  349. if h, err := strconv.ParseFloat(args[1], 64); err == nil && h >= 0 {
  350. po.Crop.Height = h
  351. } else {
  352. return fmt.Errorf("Invalid crop height: %s", args[1])
  353. }
  354. }
  355. if len(args) > 2 {
  356. return parseGravity(&po.Crop.Gravity, args[2:])
  357. }
  358. return nil
  359. }
  360. func applyPaddingOption(po *ProcessingOptions, args []string) error {
  361. nArgs := len(args)
  362. if nArgs < 1 || nArgs > 4 {
  363. return fmt.Errorf("Invalid padding arguments: %v", args)
  364. }
  365. po.Padding.Enabled = true
  366. if nArgs > 0 && len(args[0]) > 0 {
  367. if err := parseDimension(&po.Padding.Top, "padding top (+all)", args[0]); err != nil {
  368. return err
  369. }
  370. po.Padding.Right = po.Padding.Top
  371. po.Padding.Bottom = po.Padding.Top
  372. po.Padding.Left = po.Padding.Top
  373. }
  374. if nArgs > 1 && len(args[1]) > 0 {
  375. if err := parseDimension(&po.Padding.Right, "padding right (+left)", args[1]); err != nil {
  376. return err
  377. }
  378. po.Padding.Left = po.Padding.Right
  379. }
  380. if nArgs > 2 && len(args[2]) > 0 {
  381. if err := parseDimension(&po.Padding.Bottom, "padding bottom", args[2]); err != nil {
  382. return err
  383. }
  384. }
  385. if nArgs > 3 && len(args[3]) > 0 {
  386. if err := parseDimension(&po.Padding.Left, "padding left", args[3]); err != nil {
  387. return err
  388. }
  389. }
  390. if po.Padding.Top == 0 && po.Padding.Right == 0 && po.Padding.Bottom == 0 && po.Padding.Left == 0 {
  391. po.Padding.Enabled = false
  392. }
  393. return nil
  394. }
  395. func applyTrimOption(po *ProcessingOptions, args []string) error {
  396. nArgs := len(args)
  397. if nArgs > 4 {
  398. return fmt.Errorf("Invalid trim arguments: %v", args)
  399. }
  400. if t, err := strconv.ParseFloat(args[0], 64); err == nil && t >= 0 {
  401. po.Trim.Enabled = true
  402. po.Trim.Threshold = t
  403. } else {
  404. return fmt.Errorf("Invalid trim threshold: %s", args[0])
  405. }
  406. if nArgs > 1 && len(args[1]) > 0 {
  407. if c, err := vips.ColorFromHex(args[1]); err == nil {
  408. po.Trim.Color = c
  409. po.Trim.Smart = false
  410. } else {
  411. return fmt.Errorf("Invalid trim color: %s", args[1])
  412. }
  413. }
  414. if nArgs > 2 && len(args[2]) > 0 {
  415. po.Trim.EqualHor = parseBoolOption(args[2])
  416. }
  417. if nArgs > 3 && len(args[3]) > 0 {
  418. po.Trim.EqualVer = parseBoolOption(args[3])
  419. }
  420. return nil
  421. }
  422. func applyRotateOption(po *ProcessingOptions, args []string) error {
  423. if len(args) > 1 {
  424. return fmt.Errorf("Invalid rotate arguments: %v", args)
  425. }
  426. if r, err := strconv.Atoi(args[0]); err == nil && r%90 == 0 {
  427. po.Rotate = r
  428. } else {
  429. return fmt.Errorf("Invalid rotation angle: %s", args[0])
  430. }
  431. return nil
  432. }
  433. func applyQualityOption(po *ProcessingOptions, args []string) error {
  434. if len(args) > 1 {
  435. return fmt.Errorf("Invalid quality arguments: %v", args)
  436. }
  437. if q, err := strconv.Atoi(args[0]); err == nil && q >= 0 && q <= 100 {
  438. po.Quality = q
  439. } else {
  440. return fmt.Errorf("Invalid quality: %s", args[0])
  441. }
  442. return nil
  443. }
  444. func applyFormatQualityOption(po *ProcessingOptions, args []string) error {
  445. argsLen := len(args)
  446. if len(args)%2 != 0 {
  447. return fmt.Errorf("Missing quality for: %s", args[argsLen-1])
  448. }
  449. for i := 0; i < argsLen; i += 2 {
  450. f, ok := imagetype.Types[args[i]]
  451. if !ok {
  452. return fmt.Errorf("Invalid image format: %s", args[i])
  453. }
  454. if q, err := strconv.Atoi(args[i+1]); err == nil && q >= 0 && q <= 100 {
  455. po.FormatQuality[f] = q
  456. } else {
  457. return fmt.Errorf("Invalid quality for %s: %s", args[i], args[i+1])
  458. }
  459. }
  460. return nil
  461. }
  462. func applyMaxBytesOption(po *ProcessingOptions, args []string) error {
  463. if len(args) > 1 {
  464. return fmt.Errorf("Invalid max_bytes arguments: %v", args)
  465. }
  466. if max, err := strconv.Atoi(args[0]); err == nil && max >= 0 {
  467. po.MaxBytes = max
  468. } else {
  469. return fmt.Errorf("Invalid max_bytes: %s", args[0])
  470. }
  471. return nil
  472. }
  473. func applyBackgroundOption(po *ProcessingOptions, args []string) error {
  474. switch len(args) {
  475. case 1:
  476. if len(args[0]) == 0 {
  477. po.Flatten = false
  478. } else if c, err := vips.ColorFromHex(args[0]); err == nil {
  479. po.Flatten = true
  480. po.Background = c
  481. } else {
  482. return fmt.Errorf("Invalid background argument: %s", err)
  483. }
  484. case 3:
  485. po.Flatten = true
  486. if r, err := strconv.ParseUint(args[0], 10, 8); err == nil && r <= 255 {
  487. po.Background.R = uint8(r)
  488. } else {
  489. return fmt.Errorf("Invalid background red channel: %s", args[0])
  490. }
  491. if g, err := strconv.ParseUint(args[1], 10, 8); err == nil && g <= 255 {
  492. po.Background.G = uint8(g)
  493. } else {
  494. return fmt.Errorf("Invalid background green channel: %s", args[1])
  495. }
  496. if b, err := strconv.ParseUint(args[2], 10, 8); err == nil && b <= 255 {
  497. po.Background.B = uint8(b)
  498. } else {
  499. return fmt.Errorf("Invalid background blue channel: %s", args[2])
  500. }
  501. default:
  502. return fmt.Errorf("Invalid background arguments: %v", args)
  503. }
  504. return nil
  505. }
  506. func applyBlurOption(po *ProcessingOptions, args []string) error {
  507. if len(args) > 1 {
  508. return fmt.Errorf("Invalid blur arguments: %v", args)
  509. }
  510. if b, err := strconv.ParseFloat(args[0], 32); err == nil && b >= 0 {
  511. po.Blur = float32(b)
  512. } else {
  513. return fmt.Errorf("Invalid blur: %s", args[0])
  514. }
  515. return nil
  516. }
  517. func applySharpenOption(po *ProcessingOptions, args []string) error {
  518. if len(args) > 1 {
  519. return fmt.Errorf("Invalid sharpen arguments: %v", args)
  520. }
  521. if s, err := strconv.ParseFloat(args[0], 32); err == nil && s >= 0 {
  522. po.Sharpen = float32(s)
  523. } else {
  524. return fmt.Errorf("Invalid sharpen: %s", args[0])
  525. }
  526. return nil
  527. }
  528. func applyPixelateOption(po *ProcessingOptions, args []string) error {
  529. if len(args) > 1 {
  530. return fmt.Errorf("Invalid pixelate arguments: %v", args)
  531. }
  532. if p, err := strconv.Atoi(args[0]); err == nil && p >= 0 {
  533. po.Pixelate = p
  534. } else {
  535. return fmt.Errorf("Invalid pixelate: %s", args[0])
  536. }
  537. return nil
  538. }
  539. func applyPresetOption(po *ProcessingOptions, args []string) error {
  540. for _, preset := range args {
  541. if p, ok := presets[preset]; ok {
  542. if po.isPresetUsed(preset) {
  543. log.Warningf("Recursive preset usage is detected: %s", preset)
  544. continue
  545. }
  546. po.UsedPresets = append(po.UsedPresets, preset)
  547. if err := applyURLOptions(po, p); err != nil {
  548. return err
  549. }
  550. } else {
  551. return fmt.Errorf("Unknown preset: %s", preset)
  552. }
  553. }
  554. return nil
  555. }
  556. func applyWatermarkOption(po *ProcessingOptions, args []string) error {
  557. if len(args) > 7 {
  558. return fmt.Errorf("Invalid watermark arguments: %v", args)
  559. }
  560. if o, err := strconv.ParseFloat(args[0], 64); err == nil && o >= 0 && o <= 1 {
  561. po.Watermark.Enabled = o > 0
  562. po.Watermark.Opacity = o
  563. } else {
  564. return fmt.Errorf("Invalid watermark opacity: %s", args[0])
  565. }
  566. if len(args) > 1 && len(args[1]) > 0 {
  567. if args[1] == "re" {
  568. po.Watermark.Replicate = true
  569. } else if g, ok := gravityTypes[args[1]]; ok && g != GravityFocusPoint && g != GravitySmart {
  570. po.Watermark.Gravity.Type = g
  571. } else {
  572. return fmt.Errorf("Invalid watermark position: %s", args[1])
  573. }
  574. }
  575. if len(args) > 2 && len(args[2]) > 0 {
  576. if x, err := strconv.Atoi(args[2]); err == nil {
  577. po.Watermark.Gravity.X = float64(x)
  578. } else {
  579. return fmt.Errorf("Invalid watermark X offset: %s", args[2])
  580. }
  581. }
  582. if len(args) > 3 && len(args[3]) > 0 {
  583. if y, err := strconv.Atoi(args[3]); err == nil {
  584. po.Watermark.Gravity.Y = float64(y)
  585. } else {
  586. return fmt.Errorf("Invalid watermark Y offset: %s", args[3])
  587. }
  588. }
  589. if len(args) > 4 && len(args[4]) > 0 {
  590. if s, err := strconv.ParseFloat(args[4], 64); err == nil && s >= 0 {
  591. po.Watermark.Scale = s
  592. } else {
  593. return fmt.Errorf("Invalid watermark scale: %s", args[4])
  594. }
  595. }
  596. return nil
  597. }
  598. func applyFormatOption(po *ProcessingOptions, args []string) error {
  599. if len(args) > 1 {
  600. return fmt.Errorf("Invalid format arguments: %v", args)
  601. }
  602. if f, ok := imagetype.Types[args[0]]; ok {
  603. po.Format = f
  604. } else {
  605. return fmt.Errorf("Invalid image format: %s", args[0])
  606. }
  607. return nil
  608. }
  609. func applyCacheBusterOption(po *ProcessingOptions, args []string) error {
  610. if len(args) > 1 {
  611. return fmt.Errorf("Invalid cache buster arguments: %v", args)
  612. }
  613. po.CacheBuster = args[0]
  614. return nil
  615. }
  616. func applySkipProcessingFormatsOption(po *ProcessingOptions, args []string) error {
  617. for _, format := range args {
  618. if f, ok := imagetype.Types[format]; ok {
  619. po.SkipProcessingFormats = append(po.SkipProcessingFormats, f)
  620. } else {
  621. return fmt.Errorf("Invalid image format in skip processing: %s", format)
  622. }
  623. }
  624. return nil
  625. }
  626. func applyFilenameOption(po *ProcessingOptions, args []string) error {
  627. if len(args) > 1 {
  628. return fmt.Errorf("Invalid filename arguments: %v", args)
  629. }
  630. po.Filename = args[0]
  631. return nil
  632. }
  633. func applyExpiresOption(po *ProcessingOptions, args []string) error {
  634. if len(args) > 1 {
  635. return fmt.Errorf("Invalid expires arguments: %v", args)
  636. }
  637. timestamp, err := strconv.ParseInt(args[0], 10, 64)
  638. if err != nil {
  639. return fmt.Errorf("Invalid expires argument: %v", args[0])
  640. }
  641. if timestamp > 0 && timestamp < time.Now().Unix() {
  642. return errExpiredURL
  643. }
  644. return nil
  645. }
  646. func applyStripMetadataOption(po *ProcessingOptions, args []string) error {
  647. if len(args) > 1 {
  648. return fmt.Errorf("Invalid strip metadata arguments: %v", args)
  649. }
  650. po.StripMetadata = parseBoolOption(args[0])
  651. return nil
  652. }
  653. func applyKeepCopyrightOption(po *ProcessingOptions, args []string) error {
  654. if len(args) > 1 {
  655. return fmt.Errorf("Invalid keep copyright arguments: %v", args)
  656. }
  657. po.KeepCopyright = parseBoolOption(args[0])
  658. return nil
  659. }
  660. func applyStripColorProfileOption(po *ProcessingOptions, args []string) error {
  661. if len(args) > 1 {
  662. return fmt.Errorf("Invalid strip color profile arguments: %v", args)
  663. }
  664. po.StripColorProfile = parseBoolOption(args[0])
  665. return nil
  666. }
  667. func applyAutoRotateOption(po *ProcessingOptions, args []string) error {
  668. if len(args) > 1 {
  669. return fmt.Errorf("Invalid auto rotate arguments: %v", args)
  670. }
  671. po.AutoRotate = parseBoolOption(args[0])
  672. return nil
  673. }
  674. func applyEnforceThumbnailOption(po *ProcessingOptions, args []string) error {
  675. if len(args) > 1 {
  676. return fmt.Errorf("Invalid enforce thumbnail arguments: %v", args)
  677. }
  678. po.EnforceThumbnail = parseBoolOption(args[0])
  679. return nil
  680. }
  681. func applyReturnAttachmentOption(po *ProcessingOptions, args []string) error {
  682. if len(args) > 1 {
  683. return fmt.Errorf("Invalid return_attachment arguments: %v", args)
  684. }
  685. po.ReturnAttachment = parseBoolOption(args[0])
  686. return nil
  687. }
  688. func applyURLOption(po *ProcessingOptions, name string, args []string) error {
  689. switch name {
  690. case "resize", "rs":
  691. return applyResizeOption(po, args)
  692. case "size", "s":
  693. return applySizeOption(po, args)
  694. case "resizing_type", "rt":
  695. return applyResizingTypeOption(po, args)
  696. case "width", "w":
  697. return applyWidthOption(po, args)
  698. case "height", "h":
  699. return applyHeightOption(po, args)
  700. case "min-width", "mw":
  701. return applyMinWidthOption(po, args)
  702. case "min-height", "mh":
  703. return applyMinHeightOption(po, args)
  704. case "zoom", "z":
  705. return applyZoomOption(po, args)
  706. case "dpr":
  707. return applyDprOption(po, args)
  708. case "enlarge", "el":
  709. return applyEnlargeOption(po, args)
  710. case "extend", "ex":
  711. return applyExtendOption(po, args)
  712. case "gravity", "g":
  713. return applyGravityOption(po, args)
  714. case "crop", "c":
  715. return applyCropOption(po, args)
  716. case "trim", "t":
  717. return applyTrimOption(po, args)
  718. case "padding", "pd":
  719. return applyPaddingOption(po, args)
  720. case "auto_rotate", "ar":
  721. return applyAutoRotateOption(po, args)
  722. case "rotate", "rot":
  723. return applyRotateOption(po, args)
  724. case "background", "bg":
  725. return applyBackgroundOption(po, args)
  726. case "blur", "bl":
  727. return applyBlurOption(po, args)
  728. case "sharpen", "sh":
  729. return applySharpenOption(po, args)
  730. case "pixelate", "pix":
  731. return applyPixelateOption(po, args)
  732. case "watermark", "wm":
  733. return applyWatermarkOption(po, args)
  734. case "strip_metadata", "sm":
  735. return applyStripMetadataOption(po, args)
  736. case "keep_copyright", "kcr":
  737. return applyKeepCopyrightOption(po, args)
  738. case "strip_color_profile", "scp":
  739. return applyStripColorProfileOption(po, args)
  740. case "enforce_thumbnail", "eth":
  741. return applyEnforceThumbnailOption(po, args)
  742. case "return_attachment", "att":
  743. return applyReturnAttachmentOption(po, args)
  744. // Saving options
  745. case "quality", "q":
  746. return applyQualityOption(po, args)
  747. case "format_quality", "fq":
  748. return applyFormatQualityOption(po, args)
  749. case "max_bytes", "mb":
  750. return applyMaxBytesOption(po, args)
  751. case "format", "f", "ext":
  752. return applyFormatOption(po, args)
  753. // Handling options
  754. case "skip_processing", "skp":
  755. return applySkipProcessingFormatsOption(po, args)
  756. case "cachebuster", "cb":
  757. return applyCacheBusterOption(po, args)
  758. case "expires", "exp":
  759. return applyExpiresOption(po, args)
  760. case "filename", "fn":
  761. return applyFilenameOption(po, args)
  762. // Presets
  763. case "preset", "pr":
  764. return applyPresetOption(po, args)
  765. }
  766. return fmt.Errorf("Unknown processing option: %s", name)
  767. }
  768. func applyURLOptions(po *ProcessingOptions, options urlOptions) error {
  769. for _, opt := range options {
  770. if err := applyURLOption(po, opt.Name, opt.Args); err != nil {
  771. return err
  772. }
  773. }
  774. return nil
  775. }
  776. func defaultProcessingOptions(headers http.Header) (*ProcessingOptions, error) {
  777. po := NewProcessingOptions()
  778. headerAccept := headers.Get("Accept")
  779. if strings.Contains(headerAccept, "image/webp") {
  780. po.PreferWebP = config.EnableWebpDetection || config.EnforceWebp
  781. po.EnforceWebP = config.EnforceWebp
  782. }
  783. if strings.Contains(headerAccept, "image/avif") {
  784. po.PreferAvif = config.EnableAvifDetection || config.EnforceAvif
  785. po.EnforceAvif = config.EnforceAvif
  786. }
  787. if config.EnableClientHints {
  788. if headerDPR := headers.Get("DPR"); len(headerDPR) > 0 {
  789. if dpr, err := strconv.ParseFloat(headerDPR, 64); err == nil && (dpr > 0 && dpr <= maxClientHintDPR) {
  790. po.Dpr = dpr
  791. }
  792. }
  793. if headerViewportWidth := headers.Get("Viewport-Width"); len(headerViewportWidth) > 0 {
  794. if vw, err := strconv.Atoi(headerViewportWidth); err == nil {
  795. po.Width = vw
  796. }
  797. }
  798. if headerWidth := headers.Get("Width"); len(headerWidth) > 0 {
  799. if w, err := strconv.Atoi(headerWidth); err == nil {
  800. po.Width = imath.Scale(w, 1/po.Dpr)
  801. }
  802. }
  803. }
  804. if _, ok := presets["default"]; ok {
  805. if err := applyPresetOption(po, []string{"default"}); err != nil {
  806. return po, err
  807. }
  808. }
  809. return po, nil
  810. }
  811. func parsePathOptions(parts []string, headers http.Header) (*ProcessingOptions, string, error) {
  812. if _, ok := resizeTypes[parts[0]]; ok {
  813. return nil, "", ierrors.New(
  814. 404,
  815. "It looks like you're using the deprecated basic URL format",
  816. "Invalid URL",
  817. )
  818. }
  819. po, err := defaultProcessingOptions(headers)
  820. if err != nil {
  821. return nil, "", err
  822. }
  823. options, urlParts := parseURLOptions(parts)
  824. if err = applyURLOptions(po, options); err != nil {
  825. return nil, "", err
  826. }
  827. url, extension, err := DecodeURL(urlParts)
  828. if err != nil {
  829. return nil, "", err
  830. }
  831. if len(extension) > 0 {
  832. if err = applyFormatOption(po, []string{extension}); err != nil {
  833. return nil, "", err
  834. }
  835. }
  836. return po, url, nil
  837. }
  838. func parsePathPresets(parts []string, headers http.Header) (*ProcessingOptions, string, error) {
  839. po, err := defaultProcessingOptions(headers)
  840. if err != nil {
  841. return nil, "", err
  842. }
  843. presets := strings.Split(parts[0], ":")
  844. urlParts := parts[1:]
  845. if err = applyPresetOption(po, presets); err != nil {
  846. return nil, "", err
  847. }
  848. url, extension, err := DecodeURL(urlParts)
  849. if err != nil {
  850. return nil, "", err
  851. }
  852. if len(extension) > 0 {
  853. if err = applyFormatOption(po, []string{extension}); err != nil {
  854. return nil, "", err
  855. }
  856. }
  857. return po, url, nil
  858. }
  859. func ParsePath(path string, headers http.Header) (*ProcessingOptions, string, error) {
  860. if path == "" || path == "/" {
  861. return nil, "", ierrors.New(404, fmt.Sprintf("Invalid path: %s", path), "Invalid URL")
  862. }
  863. parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
  864. var (
  865. imageURL string
  866. po *ProcessingOptions
  867. err error
  868. )
  869. if config.OnlyPresets {
  870. po, imageURL, err = parsePathPresets(parts, headers)
  871. } else {
  872. po, imageURL, err = parsePathOptions(parts, headers)
  873. }
  874. if err != nil {
  875. return nil, "", ierrors.New(404, err.Error(), "Invalid URL")
  876. }
  877. return po, imageURL, nil
  878. }