processing_options.go 25 KB

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