image_proxy.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2020 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package proxy // import "miniflux.app/proxy"
  5. import (
  6. "strings"
  7. "miniflux.app/config"
  8. "miniflux.app/url"
  9. "github.com/PuerkitoBio/goquery"
  10. "github.com/gorilla/mux"
  11. )
  12. // ImageProxyRewriter replaces image URLs with internal proxy URLs.
  13. func ImageProxyRewriter(router *mux.Router, data string) string {
  14. proxyImages := config.Opts.ProxyImages()
  15. if proxyImages == "none" {
  16. return data
  17. }
  18. doc, err := goquery.NewDocumentFromReader(strings.NewReader(data))
  19. if err != nil {
  20. return data
  21. }
  22. doc.Find("img").Each(func(i int, img *goquery.Selection) {
  23. if srcAttr, ok := img.Attr("src"); ok {
  24. if proxyImages == "all" || !url.IsHTTPS(srcAttr) {
  25. img.SetAttr("src", ProxifyURL(router, srcAttr))
  26. }
  27. }
  28. if srcsetAttr, ok := img.Attr("srcset"); ok {
  29. if proxyImages == "all" || !url.IsHTTPS(srcsetAttr) {
  30. proxifySourceSet(img, router, srcsetAttr)
  31. }
  32. }
  33. })
  34. doc.Find("picture source").Each(func(i int, sourceElement *goquery.Selection) {
  35. if srcsetAttr, ok := sourceElement.Attr("srcset"); ok {
  36. if proxyImages == "all" || !url.IsHTTPS(srcsetAttr) {
  37. proxifySourceSet(sourceElement, router, srcsetAttr)
  38. }
  39. }
  40. })
  41. output, err := doc.Find("body").First().Html()
  42. if err != nil {
  43. return data
  44. }
  45. return output
  46. }
  47. func proxifySourceSet(element *goquery.Selection, router *mux.Router, attributeValue string) {
  48. var proxifiedSources []string
  49. for _, source := range strings.Split(attributeValue, ",") {
  50. parts := strings.Split(strings.TrimSpace(source), " ")
  51. nbParts := len(parts)
  52. if nbParts > 0 {
  53. source = ProxifyURL(router, parts[0])
  54. if nbParts > 1 {
  55. source += " " + parts[1]
  56. }
  57. proxifiedSources = append(proxifiedSources, source)
  58. }
  59. }
  60. if len(proxifiedSources) > 0 {
  61. element.SetAttr("srcset", strings.Join(proxifiedSources, ", "))
  62. }
  63. }