finder.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package icon // import "miniflux.app/v2/internal/reader/icon"
  4. import (
  5. "bytes"
  6. "encoding/base64"
  7. "fmt"
  8. "image"
  9. "image/gif"
  10. "image/jpeg"
  11. "image/png"
  12. "io"
  13. "log/slog"
  14. "net/url"
  15. "regexp"
  16. "slices"
  17. "strings"
  18. "miniflux.app/v2/internal/config"
  19. "miniflux.app/v2/internal/crypto"
  20. "miniflux.app/v2/internal/model"
  21. "miniflux.app/v2/internal/reader/encoding"
  22. "miniflux.app/v2/internal/reader/fetcher"
  23. "miniflux.app/v2/internal/urllib"
  24. "github.com/PuerkitoBio/goquery"
  25. "github.com/tdewolff/minify/v2"
  26. "github.com/tdewolff/minify/v2/svg"
  27. "golang.org/x/image/draw"
  28. "golang.org/x/image/webp"
  29. )
  30. type iconFinder struct {
  31. requestBuilder *fetcher.RequestBuilder
  32. websiteURL string
  33. feedIconURL string
  34. }
  35. func newIconFinder(requestBuilder *fetcher.RequestBuilder, websiteURL, feedIconURL string) *iconFinder {
  36. return &iconFinder{
  37. requestBuilder: requestBuilder,
  38. websiteURL: websiteURL,
  39. feedIconURL: feedIconURL,
  40. }
  41. }
  42. func (f *iconFinder) findIcon() (*model.Icon, error) {
  43. slog.Debug("Begin icon discovery process",
  44. slog.String("website_url", f.websiteURL),
  45. slog.String("feed_icon_url", f.feedIconURL),
  46. )
  47. if f.feedIconURL != "" {
  48. if icon, err := f.fetchFeedIcon(); err != nil {
  49. slog.Debug("Unable to download icon from feed",
  50. slog.String("website_url", f.websiteURL),
  51. slog.String("feed_icon_url", f.feedIconURL),
  52. slog.Any("error", err),
  53. )
  54. } else if icon != nil {
  55. return icon, nil
  56. }
  57. }
  58. if icon, err := f.fetchIconsFromHTMLDocument(); err != nil {
  59. slog.Debug("Unable to fetch icons from HTML document",
  60. slog.String("website_url", f.websiteURL),
  61. slog.Any("error", err),
  62. )
  63. } else if icon != nil {
  64. return icon, nil
  65. }
  66. return f.fetchDefaultIcon()
  67. }
  68. func (f *iconFinder) fetchDefaultIcon() (*model.Icon, error) {
  69. slog.Debug("Fetching default icon",
  70. slog.String("website_url", f.websiteURL),
  71. )
  72. iconURL, err := urllib.JoinBaseURLAndPath(urllib.RootURL(f.websiteURL), "favicon.ico")
  73. if err != nil {
  74. return nil, fmt.Errorf(`icon: unable to join root URL and path: %w`, err)
  75. }
  76. icon, err := f.downloadIcon(iconURL)
  77. if err != nil {
  78. return nil, err
  79. }
  80. return icon, nil
  81. }
  82. func (f *iconFinder) fetchFeedIcon() (*model.Icon, error) {
  83. slog.Debug("Fetching feed icon",
  84. slog.String("website_url", f.websiteURL),
  85. slog.String("feed_icon_url", f.feedIconURL),
  86. )
  87. iconURL, err := urllib.AbsoluteURL(f.websiteURL, f.feedIconURL)
  88. if err != nil {
  89. return nil, fmt.Errorf(`icon: unable to convert icon URL to absolute URL: %w`, err)
  90. }
  91. return f.downloadIcon(iconURL)
  92. }
  93. func (f *iconFinder) fetchIconsFromHTMLDocument() (*model.Icon, error) {
  94. slog.Debug("Searching icons from HTML document",
  95. slog.String("website_url", f.websiteURL),
  96. )
  97. rootURL := urllib.RootURL(f.websiteURL)
  98. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(rootURL))
  99. defer responseHandler.Close()
  100. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  101. return nil, fmt.Errorf("icon: unable to download website index page: %w", localizedError.Error())
  102. }
  103. iconURLs, err := findIconURLsFromHTMLDocument(
  104. responseHandler.Body(config.Opts.HTTPClientMaxBodySize()),
  105. responseHandler.ContentType(),
  106. )
  107. if err != nil {
  108. return nil, err
  109. }
  110. slog.Debug("Searched icon from HTML document",
  111. slog.String("website_url", f.websiteURL),
  112. slog.String("icon_urls", strings.Join(iconURLs, ",")),
  113. )
  114. for _, iconURL := range iconURLs {
  115. if strings.HasPrefix(iconURL, "data:") {
  116. slog.Debug("Found icon with data URL",
  117. slog.String("website_url", f.websiteURL),
  118. )
  119. return parseImageDataURL(iconURL)
  120. }
  121. iconURL, err = urllib.AbsoluteURL(f.websiteURL, iconURL)
  122. if err != nil {
  123. return nil, fmt.Errorf(`icon: unable to convert icon URL to absolute URL: %w`, err)
  124. }
  125. if icon, err := f.downloadIcon(iconURL); err != nil {
  126. slog.Debug("Unable to download icon from HTML document",
  127. slog.String("website_url", f.websiteURL),
  128. slog.String("icon_url", iconURL),
  129. slog.Any("error", err),
  130. )
  131. } else if icon != nil {
  132. slog.Debug("Downloaded icon from HTML document",
  133. slog.String("website_url", f.websiteURL),
  134. slog.String("icon_url", iconURL),
  135. )
  136. return icon, nil
  137. }
  138. }
  139. return nil, nil
  140. }
  141. func (f *iconFinder) downloadIcon(iconURL string) (*model.Icon, error) {
  142. slog.Debug("Downloading icon",
  143. slog.String("website_url", f.websiteURL),
  144. slog.String("icon_url", iconURL),
  145. )
  146. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(iconURL))
  147. defer responseHandler.Close()
  148. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  149. return nil, fmt.Errorf("icon: unable to download website icon: %w", localizedError.Error())
  150. }
  151. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  152. if localizedError != nil {
  153. return nil, fmt.Errorf("icon: unable to read response body: %w", localizedError.Error())
  154. }
  155. icon := &model.Icon{
  156. Hash: crypto.HashFromBytes(responseBody),
  157. MimeType: responseHandler.ContentType(),
  158. Content: responseBody,
  159. }
  160. icon = resizeIcon(icon)
  161. return icon, nil
  162. }
  163. func resizeIcon(icon *model.Icon) *model.Icon {
  164. if icon.MimeType == "image/svg+xml" {
  165. minifier := minify.New()
  166. minifier.AddFunc("image/svg+xml", svg.Minify)
  167. var err error
  168. // minifier.Bytes returns the data unchanged in case of error.
  169. icon.Content, err = minifier.Bytes("image/svg+xml", icon.Content)
  170. if err != nil {
  171. slog.Error("Unable to minify SVG icon", slog.Any("error", err))
  172. }
  173. return icon
  174. }
  175. if !slices.Contains([]string{"image/jpeg", "image/png", "image/gif", "image/webp"}, icon.MimeType) {
  176. slog.Info("Icon resize skipped: unsupported MIME type", slog.String("mime_type", icon.MimeType))
  177. return icon
  178. }
  179. r := bytes.NewReader(icon.Content)
  180. // Don't resize icons that we can't decode, or that already have the right size.
  181. config, _, err := image.DecodeConfig(r)
  182. if err != nil {
  183. slog.Warn("Unable to decode icon metadata", slog.Any("error", err))
  184. return icon
  185. }
  186. if config.Height <= 32 && config.Width <= 32 {
  187. slog.Debug("Icon doesn't need to be resized", slog.Int("height", config.Height), slog.Int("width", config.Width))
  188. return icon
  189. }
  190. r.Seek(0, io.SeekStart)
  191. var src image.Image
  192. switch icon.MimeType {
  193. case "image/jpeg":
  194. src, err = jpeg.Decode(r)
  195. case "image/png":
  196. src, err = png.Decode(r)
  197. case "image/gif":
  198. src, err = gif.Decode(r)
  199. case "image/webp":
  200. src, err = webp.Decode(r)
  201. }
  202. if err != nil || src == nil {
  203. slog.Warn("Unable to decode icon image", slog.Any("error", err))
  204. return icon
  205. }
  206. dst := image.NewRGBA(image.Rect(0, 0, 32, 32))
  207. draw.BiLinear.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)
  208. var b bytes.Buffer
  209. if err = png.Encode(io.Writer(&b), dst); err != nil {
  210. slog.Warn("Unable to encode resized icon", slog.Any("error", err))
  211. return icon
  212. }
  213. icon.Content = b.Bytes()
  214. icon.MimeType = "image/png"
  215. return icon
  216. }
  217. func findIconURLsFromHTMLDocument(body io.Reader, contentType string) ([]string, error) {
  218. htmlDocumentReader, err := encoding.NewCharsetReader(body, contentType)
  219. if err != nil {
  220. return nil, fmt.Errorf("icon: unable to create charset reader: %w", err)
  221. }
  222. doc, err := goquery.NewDocumentFromReader(htmlDocumentReader)
  223. if err != nil {
  224. return nil, fmt.Errorf("icon: unable to read document: %v", err)
  225. }
  226. queries := [...]string{
  227. "link[rel='icon' i][href]",
  228. "link[rel='shortcut icon' i][href]",
  229. "link[rel='icon shortcut' i][href]",
  230. "link[rel='apple-touch-icon'][href]",
  231. }
  232. var iconURLs []string
  233. for _, query := range queries {
  234. slog.Debug("Searching icon URL in HTML document", slog.String("query", query))
  235. for _, s := range doc.Find(query).EachIter() {
  236. href, _ := s.Attr("href")
  237. if iconURL := strings.TrimSpace(href); iconURL != "" {
  238. iconURLs = append(iconURLs, iconURL)
  239. slog.Debug("Found icon URL in HTML document",
  240. slog.String("query", query),
  241. slog.String("icon_url", iconURL))
  242. }
  243. }
  244. }
  245. return iconURLs, nil
  246. }
  247. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs#syntax
  248. // data:[<mediatype>][;encoding],<data>
  249. // we consider <mediatype> to be mandatory, and it has to start with `image/`.
  250. // we consider `base64`, `utf8` and the empty string to be the only valid encodings
  251. func parseImageDataURL(value string) (*model.Icon, error) {
  252. re := regexp.MustCompile(`^data:` +
  253. `(?P<mediatype>image/[^;,]+)` +
  254. `(?:;(?P<encoding>base64|utf8))?` +
  255. `,(?P<data>.+)$`)
  256. matches := re.FindStringSubmatch(value)
  257. if matches == nil {
  258. return nil, fmt.Errorf(`icon: invalid data URL %q`, value)
  259. }
  260. mediaType := matches[re.SubexpIndex("mediatype")]
  261. encoding := matches[re.SubexpIndex("encoding")]
  262. data := matches[re.SubexpIndex("data")]
  263. var blob []byte
  264. switch encoding {
  265. case "base64":
  266. var err error
  267. blob, err = base64.StdEncoding.DecodeString(data)
  268. if err != nil {
  269. return nil, fmt.Errorf(`icon: invalid data %q (%v)`, value, err)
  270. }
  271. case "":
  272. decodedData, err := url.QueryUnescape(data)
  273. if err != nil {
  274. return nil, fmt.Errorf(`icon: unable to decode data URL %q`, value)
  275. }
  276. blob = []byte(decodedData)
  277. case "utf8":
  278. blob = []byte(data)
  279. }
  280. return &model.Icon{
  281. Hash: crypto.HashFromBytes(blob),
  282. Content: blob,
  283. MimeType: mediaType,
  284. }, nil
  285. }