finder.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. // Copyright 2017 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 icon // import "miniflux.app/reader/icon"
  5. import (
  6. "encoding/base64"
  7. "fmt"
  8. "io"
  9. "strings"
  10. "miniflux.app/config"
  11. "miniflux.app/crypto"
  12. "miniflux.app/http/client"
  13. "miniflux.app/logger"
  14. "miniflux.app/model"
  15. "miniflux.app/url"
  16. "github.com/PuerkitoBio/goquery"
  17. )
  18. // FindIcon try to find the website's icon.
  19. func FindIcon(websiteURL, userAgent string, fetchViaProxy, allowSelfSignedCertificates bool) (*model.Icon, error) {
  20. rootURL := url.RootURL(websiteURL)
  21. logger.Debug("[FindIcon] Trying to find an icon: rootURL=%q websiteURL=%q userAgent=%q", rootURL, websiteURL, userAgent)
  22. clt := client.NewClientWithConfig(rootURL, config.Opts)
  23. clt.WithUserAgent(userAgent)
  24. clt.AllowSelfSignedCertificates = allowSelfSignedCertificates
  25. if fetchViaProxy {
  26. clt.WithProxy()
  27. }
  28. response, err := clt.Get()
  29. if err != nil {
  30. return nil, fmt.Errorf("icon: unable to download website index page: %v", err)
  31. }
  32. if response.HasServerFailure() {
  33. return nil, fmt.Errorf("icon: unable to download website index page: status=%d", response.StatusCode)
  34. }
  35. iconURL, err := parseDocument(rootURL, response.Body)
  36. if err != nil {
  37. return nil, err
  38. }
  39. if strings.HasPrefix(iconURL, "data:") {
  40. return parseImageDataURL(iconURL)
  41. }
  42. logger.Debug("[FindIcon] Fetching icon => %s", iconURL)
  43. icon, err := downloadIcon(iconURL, userAgent, fetchViaProxy, allowSelfSignedCertificates)
  44. if err != nil {
  45. return nil, err
  46. }
  47. return icon, nil
  48. }
  49. func parseDocument(websiteURL string, data io.Reader) (string, error) {
  50. queries := []string{
  51. "link[rel='shortcut icon']",
  52. "link[rel='Shortcut Icon']",
  53. "link[rel='icon shortcut']",
  54. "link[rel='icon']",
  55. }
  56. doc, err := goquery.NewDocumentFromReader(data)
  57. if err != nil {
  58. return "", fmt.Errorf("icon: unable to read document: %v", err)
  59. }
  60. var iconURL string
  61. for _, query := range queries {
  62. doc.Find(query).Each(func(i int, s *goquery.Selection) {
  63. if href, exists := s.Attr("href"); exists {
  64. iconURL = strings.TrimSpace(href)
  65. }
  66. })
  67. if iconURL != "" {
  68. break
  69. }
  70. }
  71. if iconURL == "" {
  72. iconURL = url.RootURL(websiteURL) + "favicon.ico"
  73. } else {
  74. iconURL, _ = url.AbsoluteURL(websiteURL, iconURL)
  75. }
  76. return iconURL, nil
  77. }
  78. func downloadIcon(iconURL, userAgent string, fetchViaProxy, allowSelfSignedCertificates bool) (*model.Icon, error) {
  79. clt := client.NewClientWithConfig(iconURL, config.Opts)
  80. clt.WithUserAgent(userAgent)
  81. clt.AllowSelfSignedCertificates = allowSelfSignedCertificates
  82. if fetchViaProxy {
  83. clt.WithProxy()
  84. }
  85. response, err := clt.Get()
  86. if err != nil {
  87. return nil, fmt.Errorf("icon: unable to download iconURL: %v", err)
  88. }
  89. if response.HasServerFailure() {
  90. return nil, fmt.Errorf("icon: unable to download icon: status=%d", response.StatusCode)
  91. }
  92. body, err := io.ReadAll(response.Body)
  93. if err != nil {
  94. return nil, fmt.Errorf("icon: unable to read downloaded icon: %v", err)
  95. }
  96. if len(body) == 0 {
  97. return nil, fmt.Errorf("icon: downloaded icon is empty, iconURL=%s", iconURL)
  98. }
  99. icon := &model.Icon{
  100. Hash: crypto.HashFromBytes(body),
  101. MimeType: response.ContentType,
  102. Content: body,
  103. }
  104. return icon, nil
  105. }
  106. func parseImageDataURL(value string) (*model.Icon, error) {
  107. colon := strings.Index(value, ":")
  108. semicolon := strings.Index(value, ";")
  109. comma := strings.Index(value, ",")
  110. if colon <= 0 || semicolon <= 0 || comma <= 0 {
  111. return nil, fmt.Errorf(`icon: invalid data url "%s"`, value)
  112. }
  113. mimeType := value[colon+1 : semicolon]
  114. encoding := value[semicolon+1 : comma]
  115. data := value[comma+1:]
  116. if encoding != "base64" {
  117. return nil, fmt.Errorf(`icon: unsupported data url encoding "%s"`, value)
  118. }
  119. if !strings.HasPrefix(mimeType, "image/") {
  120. return nil, fmt.Errorf(`icon: invalid mime type "%s"`, mimeType)
  121. }
  122. blob, err := base64.StdEncoding.DecodeString(data)
  123. if err != nil {
  124. return nil, fmt.Errorf(`icon: invalid data "%s" (%v)`, value, err)
  125. }
  126. if len(blob) == 0 {
  127. return nil, fmt.Errorf(`icon: empty data "%s"`, value)
  128. }
  129. icon := &model.Icon{
  130. Hash: crypto.HashFromBytes(blob),
  131. Content: blob,
  132. MimeType: mimeType,
  133. }
  134. return icon, nil
  135. }