processing_options.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  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. SkipProcessingFormats []imagetype.Type
  81. CacheBuster string
  82. Watermark WatermarkOptions
  83. PreferWebP bool
  84. EnforceWebP bool
  85. PreferAvif bool
  86. EnforceAvif bool
  87. Filename string
  88. ReturnAttachment bool
  89. Raw bool
  90. UsedPresets []string
  91. defaultQuality int
  92. }
  93. func NewProcessingOptions() *ProcessingOptions {
  94. po := ProcessingOptions{
  95. ResizingType: ResizeFit,
  96. Width: 0,
  97. Height: 0,
  98. ZoomWidth: 1,
  99. ZoomHeight: 1,
  100. Gravity: GravityOptions{Type: GravityCenter},
  101. Enlarge: false,
  102. Extend: ExtendOptions{Enabled: false, Gravity: GravityOptions{Type: GravityCenter}},
  103. Padding: PaddingOptions{Enabled: false},
  104. Trim: TrimOptions{Enabled: false, Threshold: 10, Smart: true},
  105. Rotate: 0,
  106. Quality: 0,
  107. MaxBytes: 0,
  108. Format: imagetype.Unknown,
  109. Background: vips.Color{R: 255, G: 255, B: 255},
  110. Blur: 0,
  111. Sharpen: 0,
  112. Dpr: 1,
  113. Watermark: WatermarkOptions{Opacity: 1, Replicate: false, Gravity: GravityOptions{Type: GravityCenter}},
  114. StripMetadata: config.StripMetadata,
  115. KeepCopyright: config.KeepCopyright,
  116. StripColorProfile: config.StripColorProfile,
  117. AutoRotate: config.AutoRotate,
  118. EnforceThumbnail: config.EnforceThumbnail,
  119. ReturnAttachment: config.ReturnAttachment,
  120. SkipProcessingFormats: append([]imagetype.Type(nil), config.SkipProcessingFormats...),
  121. UsedPresets: make([]string, 0, len(config.Presets)),
  122. // Basically, we need this to update ETag when `IMGPROXY_QUALITY` is changed
  123. defaultQuality: config.Quality,
  124. }
  125. po.FormatQuality = make(map[imagetype.Type]int, len(config.FormatQuality))
  126. for k, v := range config.FormatQuality {
  127. po.FormatQuality[k] = v
  128. }
  129. return &po
  130. }
  131. func (po *ProcessingOptions) GetQuality() int {
  132. q := po.Quality
  133. if q == 0 {
  134. q = po.FormatQuality[po.Format]
  135. }
  136. if q == 0 {
  137. q = po.defaultQuality
  138. }
  139. return q
  140. }
  141. func (po *ProcessingOptions) isPresetUsed(name string) bool {
  142. for _, usedName := range po.UsedPresets {
  143. if usedName == name {
  144. return true
  145. }
  146. }
  147. return false
  148. }
  149. func (po *ProcessingOptions) Diff() structdiff.Entries {
  150. return structdiff.Diff(NewProcessingOptions(), po)
  151. }
  152. func (po *ProcessingOptions) String() string {
  153. return po.Diff().String()
  154. }
  155. func (po *ProcessingOptions) MarshalJSON() ([]byte, error) {
  156. return po.Diff().MarshalJSON()
  157. }
  158. func parseDimension(d *int, name, arg string) error {
  159. if v, err := strconv.Atoi(arg); err == nil && v >= 0 {
  160. *d = v
  161. } else {
  162. return fmt.Errorf("Invalid %s: %s", name, arg)
  163. }
  164. return nil
  165. }
  166. func parseBoolOption(str string) bool {
  167. b, err := strconv.ParseBool(str)
  168. if err != nil {
  169. log.Warningf("`%s` is not a valid boolean value. Treated as false", str)
  170. }
  171. return b
  172. }
  173. func isGravityOffcetValid(gravity GravityType, offset float64) bool {
  174. return gravity != GravityFocusPoint || (offset >= 0 && offset <= 1)
  175. }
  176. func parseGravity(g *GravityOptions, args []string) error {
  177. nArgs := len(args)
  178. if nArgs > 3 {
  179. return fmt.Errorf("Invalid gravity arguments: %v", args)
  180. }
  181. if t, ok := gravityTypes[args[0]]; ok {
  182. g.Type = t
  183. } else {
  184. return fmt.Errorf("Invalid gravity: %s", args[0])
  185. }
  186. if g.Type == GravitySmart && nArgs > 1 {
  187. return fmt.Errorf("Invalid gravity arguments: %v", args)
  188. } else if g.Type == GravityFocusPoint && nArgs != 3 {
  189. return fmt.Errorf("Invalid gravity arguments: %v", args)
  190. }
  191. if nArgs > 1 {
  192. if x, err := strconv.ParseFloat(args[1], 64); err == nil && isGravityOffcetValid(g.Type, x) {
  193. g.X = x
  194. } else {
  195. return fmt.Errorf("Invalid gravity X: %s", args[1])
  196. }
  197. }
  198. if nArgs > 2 {
  199. if y, err := strconv.ParseFloat(args[2], 64); err == nil && isGravityOffcetValid(g.Type, y) {
  200. g.Y = y
  201. } else {
  202. return fmt.Errorf("Invalid gravity Y: %s", args[2])
  203. }
  204. }
  205. return nil
  206. }
  207. func applyWidthOption(po *ProcessingOptions, args []string) error {
  208. if len(args) > 1 {
  209. return fmt.Errorf("Invalid width arguments: %v", args)
  210. }
  211. return parseDimension(&po.Width, "width", args[0])
  212. }
  213. func applyHeightOption(po *ProcessingOptions, args []string) error {
  214. if len(args) > 1 {
  215. return fmt.Errorf("Invalid height arguments: %v", args)
  216. }
  217. return parseDimension(&po.Height, "height", args[0])
  218. }
  219. func applyMinWidthOption(po *ProcessingOptions, args []string) error {
  220. if len(args) > 1 {
  221. return fmt.Errorf("Invalid min width arguments: %v", args)
  222. }
  223. return parseDimension(&po.MinWidth, "min width", args[0])
  224. }
  225. func applyMinHeightOption(po *ProcessingOptions, args []string) error {
  226. if len(args) > 1 {
  227. return fmt.Errorf("Invalid min height arguments: %v", args)
  228. }
  229. return parseDimension(&po.MinHeight, " min height", args[0])
  230. }
  231. func applyEnlargeOption(po *ProcessingOptions, args []string) error {
  232. if len(args) > 1 {
  233. return fmt.Errorf("Invalid enlarge arguments: %v", args)
  234. }
  235. po.Enlarge = parseBoolOption(args[0])
  236. return nil
  237. }
  238. func applyExtendOption(po *ProcessingOptions, args []string) error {
  239. if len(args) > 4 {
  240. return fmt.Errorf("Invalid extend arguments: %v", args)
  241. }
  242. po.Extend.Enabled = parseBoolOption(args[0])
  243. if len(args) > 1 {
  244. if err := parseGravity(&po.Extend.Gravity, args[1:]); err != nil {
  245. return err
  246. }
  247. if po.Extend.Gravity.Type == GravitySmart {
  248. return errors.New("extend doesn't support smart gravity")
  249. }
  250. }
  251. return nil
  252. }
  253. func applySizeOption(po *ProcessingOptions, args []string) (err error) {
  254. if len(args) > 7 {
  255. return fmt.Errorf("Invalid size arguments: %v", args)
  256. }
  257. if len(args) >= 1 && len(args[0]) > 0 {
  258. if err = applyWidthOption(po, args[0:1]); err != nil {
  259. return
  260. }
  261. }
  262. if len(args) >= 2 && len(args[1]) > 0 {
  263. if err = applyHeightOption(po, args[1:2]); err != nil {
  264. return
  265. }
  266. }
  267. if len(args) >= 3 && len(args[2]) > 0 {
  268. if err = applyEnlargeOption(po, args[2:3]); err != nil {
  269. return
  270. }
  271. }
  272. if len(args) >= 4 && len(args[3]) > 0 {
  273. if err = applyExtendOption(po, args[3:]); err != nil {
  274. return
  275. }
  276. }
  277. return nil
  278. }
  279. func applyResizingTypeOption(po *ProcessingOptions, args []string) error {
  280. if len(args) > 1 {
  281. return fmt.Errorf("Invalid resizing type arguments: %v", args)
  282. }
  283. if r, ok := resizeTypes[args[0]]; ok {
  284. po.ResizingType = r
  285. } else {
  286. return fmt.Errorf("Invalid resize type: %s", args[0])
  287. }
  288. return nil
  289. }
  290. func applyResizeOption(po *ProcessingOptions, args []string) error {
  291. if len(args) > 8 {
  292. return fmt.Errorf("Invalid resize arguments: %v", args)
  293. }
  294. if len(args[0]) > 0 {
  295. if err := applyResizingTypeOption(po, args[0:1]); err != nil {
  296. return err
  297. }
  298. }
  299. if len(args) > 1 {
  300. if err := applySizeOption(po, args[1:]); err != nil {
  301. return err
  302. }
  303. }
  304. return nil
  305. }
  306. func applyZoomOption(po *ProcessingOptions, args []string) error {
  307. nArgs := len(args)
  308. if nArgs > 2 {
  309. return fmt.Errorf("Invalid zoom arguments: %v", args)
  310. }
  311. if z, err := strconv.ParseFloat(args[0], 64); err == nil && z > 0 {
  312. po.ZoomWidth = z
  313. po.ZoomHeight = z
  314. } else {
  315. return fmt.Errorf("Invalid zoom value: %s", args[0])
  316. }
  317. if nArgs > 1 {
  318. if z, err := strconv.ParseFloat(args[1], 64); err == nil && z > 0 {
  319. po.ZoomHeight = z
  320. } else {
  321. return fmt.Errorf("Invalid zoom value: %s", args[0])
  322. }
  323. }
  324. return nil
  325. }
  326. func applyDprOption(po *ProcessingOptions, args []string) error {
  327. if len(args) > 1 {
  328. return fmt.Errorf("Invalid dpr arguments: %v", args)
  329. }
  330. if d, err := strconv.ParseFloat(args[0], 64); err == nil && d > 0 {
  331. po.Dpr = d
  332. } else {
  333. return fmt.Errorf("Invalid dpr: %s", args[0])
  334. }
  335. return nil
  336. }
  337. func applyGravityOption(po *ProcessingOptions, args []string) error {
  338. return parseGravity(&po.Gravity, args)
  339. }
  340. func applyCropOption(po *ProcessingOptions, args []string) error {
  341. if len(args) > 5 {
  342. return fmt.Errorf("Invalid crop arguments: %v", args)
  343. }
  344. if w, err := strconv.ParseFloat(args[0], 64); err == nil && w >= 0 {
  345. po.Crop.Width = w
  346. } else {
  347. return fmt.Errorf("Invalid crop width: %s", args[0])
  348. }
  349. if len(args) > 1 {
  350. if h, err := strconv.ParseFloat(args[1], 64); err == nil && h >= 0 {
  351. po.Crop.Height = h
  352. } else {
  353. return fmt.Errorf("Invalid crop height: %s", args[1])
  354. }
  355. }
  356. if len(args) > 2 {
  357. return parseGravity(&po.Crop.Gravity, args[2:])
  358. }
  359. return nil
  360. }
  361. func applyPaddingOption(po *ProcessingOptions, args []string) error {
  362. nArgs := len(args)
  363. if nArgs < 1 || nArgs > 4 {
  364. return fmt.Errorf("Invalid padding arguments: %v", args)
  365. }
  366. po.Padding.Enabled = true
  367. if nArgs > 0 && len(args[0]) > 0 {
  368. if err := parseDimension(&po.Padding.Top, "padding top (+all)", args[0]); err != nil {
  369. return err
  370. }
  371. po.Padding.Right = po.Padding.Top
  372. po.Padding.Bottom = po.Padding.Top
  373. po.Padding.Left = po.Padding.Top
  374. }
  375. if nArgs > 1 && len(args[1]) > 0 {
  376. if err := parseDimension(&po.Padding.Right, "padding right (+left)", args[1]); err != nil {
  377. return err
  378. }
  379. po.Padding.Left = po.Padding.Right
  380. }
  381. if nArgs > 2 && len(args[2]) > 0 {
  382. if err := parseDimension(&po.Padding.Bottom, "padding bottom", args[2]); err != nil {
  383. return err
  384. }
  385. }
  386. if nArgs > 3 && len(args[3]) > 0 {
  387. if err := parseDimension(&po.Padding.Left, "padding left", args[3]); err != nil {
  388. return err
  389. }
  390. }
  391. if po.Padding.Top == 0 && po.Padding.Right == 0 && po.Padding.Bottom == 0 && po.Padding.Left == 0 {
  392. po.Padding.Enabled = false
  393. }
  394. return nil
  395. }
  396. func applyTrimOption(po *ProcessingOptions, args []string) error {
  397. nArgs := len(args)
  398. if nArgs > 4 {
  399. return fmt.Errorf("Invalid trim arguments: %v", args)
  400. }
  401. if t, err := strconv.ParseFloat(args[0], 64); err == nil && t >= 0 {
  402. po.Trim.Enabled = true
  403. po.Trim.Threshold = t
  404. } else {
  405. return fmt.Errorf("Invalid trim threshold: %s", args[0])
  406. }
  407. if nArgs > 1 && len(args[1]) > 0 {
  408. if c, err := vips.ColorFromHex(args[1]); err == nil {
  409. po.Trim.Color = c
  410. po.Trim.Smart = false
  411. } else {
  412. return fmt.Errorf("Invalid trim color: %s", args[1])
  413. }
  414. }
  415. if nArgs > 2 && len(args[2]) > 0 {
  416. po.Trim.EqualHor = parseBoolOption(args[2])
  417. }
  418. if nArgs > 3 && len(args[3]) > 0 {
  419. po.Trim.EqualVer = parseBoolOption(args[3])
  420. }
  421. return nil
  422. }
  423. func applyRotateOption(po *ProcessingOptions, args []string) error {
  424. if len(args) > 1 {
  425. return fmt.Errorf("Invalid rotate arguments: %v", args)
  426. }
  427. if r, err := strconv.Atoi(args[0]); err == nil && r%90 == 0 {
  428. po.Rotate = r
  429. } else {
  430. return fmt.Errorf("Invalid rotation angle: %s", args[0])
  431. }
  432. return nil
  433. }
  434. func applyQualityOption(po *ProcessingOptions, args []string) error {
  435. if len(args) > 1 {
  436. return fmt.Errorf("Invalid quality arguments: %v", args)
  437. }
  438. if q, err := strconv.Atoi(args[0]); err == nil && q >= 0 && q <= 100 {
  439. po.Quality = q
  440. } else {
  441. return fmt.Errorf("Invalid quality: %s", args[0])
  442. }
  443. return nil
  444. }
  445. func applyFormatQualityOption(po *ProcessingOptions, args []string) error {
  446. argsLen := len(args)
  447. if len(args)%2 != 0 {
  448. return fmt.Errorf("Missing quality for: %s", args[argsLen-1])
  449. }
  450. for i := 0; i < argsLen; i += 2 {
  451. f, ok := imagetype.Types[args[i]]
  452. if !ok {
  453. return fmt.Errorf("Invalid image format: %s", args[i])
  454. }
  455. if q, err := strconv.Atoi(args[i+1]); err == nil && q >= 0 && q <= 100 {
  456. po.FormatQuality[f] = q
  457. } else {
  458. return fmt.Errorf("Invalid quality for %s: %s", args[i], args[i+1])
  459. }
  460. }
  461. return nil
  462. }
  463. func applyMaxBytesOption(po *ProcessingOptions, args []string) error {
  464. if len(args) > 1 {
  465. return fmt.Errorf("Invalid max_bytes arguments: %v", args)
  466. }
  467. if max, err := strconv.Atoi(args[0]); err == nil && max >= 0 {
  468. po.MaxBytes = max
  469. } else {
  470. return fmt.Errorf("Invalid max_bytes: %s", args[0])
  471. }
  472. return nil
  473. }
  474. func applyBackgroundOption(po *ProcessingOptions, args []string) error {
  475. switch len(args) {
  476. case 1:
  477. if len(args[0]) == 0 {
  478. po.Flatten = false
  479. } else if c, err := vips.ColorFromHex(args[0]); err == nil {
  480. po.Flatten = true
  481. po.Background = c
  482. } else {
  483. return fmt.Errorf("Invalid background argument: %s", err)
  484. }
  485. case 3:
  486. po.Flatten = true
  487. if r, err := strconv.ParseUint(args[0], 10, 8); err == nil && r <= 255 {
  488. po.Background.R = uint8(r)
  489. } else {
  490. return fmt.Errorf("Invalid background red channel: %s", args[0])
  491. }
  492. if g, err := strconv.ParseUint(args[1], 10, 8); err == nil && g <= 255 {
  493. po.Background.G = uint8(g)
  494. } else {
  495. return fmt.Errorf("Invalid background green channel: %s", args[1])
  496. }
  497. if b, err := strconv.ParseUint(args[2], 10, 8); err == nil && b <= 255 {
  498. po.Background.B = uint8(b)
  499. } else {
  500. return fmt.Errorf("Invalid background blue channel: %s", args[2])
  501. }
  502. default:
  503. return fmt.Errorf("Invalid background arguments: %v", args)
  504. }
  505. return nil
  506. }
  507. func applyBlurOption(po *ProcessingOptions, args []string) error {
  508. if len(args) > 1 {
  509. return fmt.Errorf("Invalid blur arguments: %v", args)
  510. }
  511. if b, err := strconv.ParseFloat(args[0], 32); err == nil && b >= 0 {
  512. po.Blur = float32(b)
  513. } else {
  514. return fmt.Errorf("Invalid blur: %s", args[0])
  515. }
  516. return nil
  517. }
  518. func applySharpenOption(po *ProcessingOptions, args []string) error {
  519. if len(args) > 1 {
  520. return fmt.Errorf("Invalid sharpen arguments: %v", args)
  521. }
  522. if s, err := strconv.ParseFloat(args[0], 32); err == nil && s >= 0 {
  523. po.Sharpen = float32(s)
  524. } else {
  525. return fmt.Errorf("Invalid sharpen: %s", args[0])
  526. }
  527. return nil
  528. }
  529. func applyPixelateOption(po *ProcessingOptions, args []string) error {
  530. if len(args) > 1 {
  531. return fmt.Errorf("Invalid pixelate arguments: %v", args)
  532. }
  533. if p, err := strconv.Atoi(args[0]); err == nil && p >= 0 {
  534. po.Pixelate = p
  535. } else {
  536. return fmt.Errorf("Invalid pixelate: %s", args[0])
  537. }
  538. return nil
  539. }
  540. func applyPresetOption(po *ProcessingOptions, args []string) error {
  541. for _, preset := range args {
  542. if p, ok := presets[preset]; ok {
  543. if po.isPresetUsed(preset) {
  544. log.Warningf("Recursive preset usage is detected: %s", preset)
  545. continue
  546. }
  547. po.UsedPresets = append(po.UsedPresets, preset)
  548. if err := applyURLOptions(po, p); err != nil {
  549. return err
  550. }
  551. } else {
  552. return fmt.Errorf("Unknown preset: %s", preset)
  553. }
  554. }
  555. return nil
  556. }
  557. func applyWatermarkOption(po *ProcessingOptions, args []string) error {
  558. if len(args) > 7 {
  559. return fmt.Errorf("Invalid watermark arguments: %v", args)
  560. }
  561. if o, err := strconv.ParseFloat(args[0], 64); err == nil && o >= 0 && o <= 1 {
  562. po.Watermark.Enabled = o > 0
  563. po.Watermark.Opacity = o
  564. } else {
  565. return fmt.Errorf("Invalid watermark opacity: %s", args[0])
  566. }
  567. if len(args) > 1 && len(args[1]) > 0 {
  568. if args[1] == "re" {
  569. po.Watermark.Replicate = true
  570. } else if g, ok := gravityTypes[args[1]]; ok && g != GravityFocusPoint && g != GravitySmart {
  571. po.Watermark.Gravity.Type = g
  572. } else {
  573. return fmt.Errorf("Invalid watermark position: %s", args[1])
  574. }
  575. }
  576. if len(args) > 2 && len(args[2]) > 0 {
  577. if x, err := strconv.Atoi(args[2]); err == nil {
  578. po.Watermark.Gravity.X = float64(x)
  579. } else {
  580. return fmt.Errorf("Invalid watermark X offset: %s", args[2])
  581. }
  582. }
  583. if len(args) > 3 && len(args[3]) > 0 {
  584. if y, err := strconv.Atoi(args[3]); err == nil {
  585. po.Watermark.Gravity.Y = float64(y)
  586. } else {
  587. return fmt.Errorf("Invalid watermark Y offset: %s", args[3])
  588. }
  589. }
  590. if len(args) > 4 && len(args[4]) > 0 {
  591. if s, err := strconv.ParseFloat(args[4], 64); err == nil && s >= 0 {
  592. po.Watermark.Scale = s
  593. } else {
  594. return fmt.Errorf("Invalid watermark scale: %s", args[4])
  595. }
  596. }
  597. return nil
  598. }
  599. func applyFormatOption(po *ProcessingOptions, args []string) error {
  600. if len(args) > 1 {
  601. return fmt.Errorf("Invalid format arguments: %v", args)
  602. }
  603. if f, ok := imagetype.Types[args[0]]; ok {
  604. po.Format = f
  605. } else {
  606. return fmt.Errorf("Invalid image format: %s", args[0])
  607. }
  608. return nil
  609. }
  610. func applyCacheBusterOption(po *ProcessingOptions, args []string) error {
  611. if len(args) > 1 {
  612. return fmt.Errorf("Invalid cache buster arguments: %v", args)
  613. }
  614. po.CacheBuster = args[0]
  615. return nil
  616. }
  617. func applySkipProcessingFormatsOption(po *ProcessingOptions, args []string) error {
  618. for _, format := range args {
  619. if f, ok := imagetype.Types[format]; ok {
  620. po.SkipProcessingFormats = append(po.SkipProcessingFormats, f)
  621. } else {
  622. return fmt.Errorf("Invalid image format in skip processing: %s", format)
  623. }
  624. }
  625. return nil
  626. }
  627. func applyRawOption(po *ProcessingOptions, args []string) error {
  628. if len(args) > 1 {
  629. return fmt.Errorf("Invalid return_attachment arguments: %v", args)
  630. }
  631. po.Raw = parseBoolOption(args[0])
  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. // Saving options
  751. case "quality", "q":
  752. return applyQualityOption(po, args)
  753. case "format_quality", "fq":
  754. return applyFormatQualityOption(po, args)
  755. case "max_bytes", "mb":
  756. return applyMaxBytesOption(po, args)
  757. case "format", "f", "ext":
  758. return applyFormatOption(po, args)
  759. // Handling options
  760. case "skip_processing", "skp":
  761. return applySkipProcessingFormatsOption(po, args)
  762. case "raw":
  763. return applyRawOption(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. case "return_attachment", "att":
  771. return applyReturnAttachmentOption(po, args)
  772. // Presets
  773. case "preset", "pr":
  774. return applyPresetOption(po, args)
  775. }
  776. return fmt.Errorf("Unknown processing option: %s", name)
  777. }
  778. func applyURLOptions(po *ProcessingOptions, options urlOptions) error {
  779. for _, opt := range options {
  780. if err := applyURLOption(po, opt.Name, opt.Args); err != nil {
  781. return err
  782. }
  783. }
  784. return nil
  785. }
  786. func defaultProcessingOptions(headers http.Header) (*ProcessingOptions, error) {
  787. po := NewProcessingOptions()
  788. headerAccept := headers.Get("Accept")
  789. if strings.Contains(headerAccept, "image/webp") {
  790. po.PreferWebP = config.EnableWebpDetection || config.EnforceWebp
  791. po.EnforceWebP = config.EnforceWebp
  792. }
  793. if strings.Contains(headerAccept, "image/avif") {
  794. po.PreferAvif = config.EnableAvifDetection || config.EnforceAvif
  795. po.EnforceAvif = config.EnforceAvif
  796. }
  797. if config.EnableClientHints {
  798. if headerDPR := headers.Get("DPR"); len(headerDPR) > 0 {
  799. if dpr, err := strconv.ParseFloat(headerDPR, 64); err == nil && (dpr > 0 && dpr <= maxClientHintDPR) {
  800. po.Dpr = dpr
  801. }
  802. }
  803. if headerViewportWidth := headers.Get("Viewport-Width"); len(headerViewportWidth) > 0 {
  804. if vw, err := strconv.Atoi(headerViewportWidth); err == nil {
  805. po.Width = vw
  806. }
  807. }
  808. if headerWidth := headers.Get("Width"); len(headerWidth) > 0 {
  809. if w, err := strconv.Atoi(headerWidth); err == nil {
  810. po.Width = imath.Scale(w, 1/po.Dpr)
  811. }
  812. }
  813. }
  814. if _, ok := presets["default"]; ok {
  815. if err := applyPresetOption(po, []string{"default"}); err != nil {
  816. return po, err
  817. }
  818. }
  819. return po, nil
  820. }
  821. func parsePathOptions(parts []string, headers http.Header) (*ProcessingOptions, string, error) {
  822. if _, ok := resizeTypes[parts[0]]; ok {
  823. return nil, "", ierrors.New(
  824. 404,
  825. "It looks like you're using the deprecated basic URL format",
  826. "Invalid URL",
  827. )
  828. }
  829. po, err := defaultProcessingOptions(headers)
  830. if err != nil {
  831. return nil, "", err
  832. }
  833. options, urlParts := parseURLOptions(parts)
  834. if err = applyURLOptions(po, options); err != nil {
  835. return nil, "", err
  836. }
  837. url, extension, err := DecodeURL(urlParts)
  838. if err != nil {
  839. return nil, "", err
  840. }
  841. if len(extension) > 0 {
  842. if err = applyFormatOption(po, []string{extension}); err != nil {
  843. return nil, "", err
  844. }
  845. }
  846. return po, url, nil
  847. }
  848. func parsePathPresets(parts []string, headers http.Header) (*ProcessingOptions, string, error) {
  849. po, err := defaultProcessingOptions(headers)
  850. if err != nil {
  851. return nil, "", err
  852. }
  853. presets := strings.Split(parts[0], ":")
  854. urlParts := parts[1:]
  855. if err = applyPresetOption(po, presets); err != nil {
  856. return nil, "", err
  857. }
  858. url, extension, err := DecodeURL(urlParts)
  859. if err != nil {
  860. return nil, "", err
  861. }
  862. if len(extension) > 0 {
  863. if err = applyFormatOption(po, []string{extension}); err != nil {
  864. return nil, "", err
  865. }
  866. }
  867. return po, url, nil
  868. }
  869. func ParsePath(path string, headers http.Header) (*ProcessingOptions, string, error) {
  870. if path == "" || path == "/" {
  871. return nil, "", ierrors.New(404, fmt.Sprintf("Invalid path: %s", path), "Invalid URL")
  872. }
  873. parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
  874. var (
  875. imageURL string
  876. po *ProcessingOptions
  877. err error
  878. )
  879. if config.OnlyPresets {
  880. po, imageURL, err = parsePathPresets(parts, headers)
  881. } else {
  882. po, imageURL, err = parsePathOptions(parts, headers)
  883. }
  884. if err != nil {
  885. return nil, "", ierrors.New(404, err.Error(), "Invalid URL")
  886. }
  887. return po, imageURL, nil
  888. }