finder.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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.downloadIcon(f.feedIconURL); err != nil {
  49. slog.Debug("Unable to fetch the feed's icon",
  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. // Try the website URL first, then fall back to the root URL if no icon is found.
  59. // The website URL may include a subdirectory (e.g., https://example.org/subfolder/), and icons can be referenced relative to that path.
  60. urls := []string{f.websiteURL}
  61. if rootURL := urllib.RootURL(f.websiteURL); rootURL != urls[0] {
  62. urls = []string{f.websiteURL, rootURL}
  63. }
  64. for _, documentURL := range urls {
  65. if icon, err := f.fetchIconsFromHTMLDocument(documentURL); err != nil {
  66. slog.Debug("Unable to fetch icons from HTML document",
  67. slog.String("document_url", documentURL),
  68. slog.Any("error", err),
  69. )
  70. } else if icon != nil {
  71. return icon, nil
  72. }
  73. }
  74. return f.fetchDefaultIcon()
  75. }
  76. func (f *iconFinder) fetchDefaultIcon() (*model.Icon, error) {
  77. slog.Debug("Fetching default icon",
  78. slog.String("website_url", f.websiteURL),
  79. )
  80. iconURL, err := urllib.JoinBaseURLAndPath(urllib.RootURL(f.websiteURL), "favicon.ico")
  81. if err != nil {
  82. return nil, fmt.Errorf(`icon: unable to join root URL and path: %w`, err)
  83. }
  84. icon, err := f.downloadIcon(iconURL)
  85. if err != nil {
  86. return nil, err
  87. }
  88. return icon, nil
  89. }
  90. func (f *iconFinder) fetchIconsFromHTMLDocument(documentURL string) (*model.Icon, error) {
  91. slog.Debug("Searching icons from HTML document",
  92. slog.String("document_url", documentURL),
  93. )
  94. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(documentURL))
  95. defer responseHandler.Close()
  96. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  97. return nil, fmt.Errorf("icon: unable to download website index page: %w", localizedError.Error())
  98. }
  99. iconURLs, err := findIconURLsFromHTMLDocument(
  100. documentURL,
  101. responseHandler.Body(config.Opts.HTTPClientMaxBodySize()),
  102. responseHandler.ContentType(),
  103. )
  104. if err != nil {
  105. return nil, err
  106. }
  107. slog.Debug("Searched icon from HTML document",
  108. slog.String("document_url", documentURL),
  109. slog.String("icon_urls", strings.Join(iconURLs, ",")),
  110. )
  111. for _, iconURL := range iconURLs {
  112. if strings.HasPrefix(iconURL, "data:") {
  113. slog.Debug("Found icon with data URL",
  114. slog.String("document_url", documentURL),
  115. )
  116. return parseImageDataURL(iconURL)
  117. }
  118. if icon, err := f.downloadIcon(iconURL); err != nil {
  119. slog.Debug("Unable to download icon from HTML document",
  120. slog.String("document_url", documentURL),
  121. slog.String("icon_url", iconURL),
  122. slog.Any("error", err),
  123. )
  124. } else if icon != nil {
  125. slog.Debug("Downloaded icon from HTML document",
  126. slog.String("document_url", documentURL),
  127. slog.String("icon_url", iconURL),
  128. )
  129. return icon, nil
  130. }
  131. }
  132. return nil, nil
  133. }
  134. func (f *iconFinder) downloadIcon(iconURL string) (*model.Icon, error) {
  135. slog.Debug("Downloading icon",
  136. slog.String("website_url", f.websiteURL),
  137. slog.String("icon_url", iconURL),
  138. )
  139. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(iconURL))
  140. defer responseHandler.Close()
  141. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  142. return nil, fmt.Errorf("icon: unable to download website icon: %w", localizedError.Error())
  143. }
  144. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  145. if localizedError != nil {
  146. return nil, fmt.Errorf("icon: unable to read response body: %w", localizedError.Error())
  147. }
  148. icon := &model.Icon{
  149. Hash: crypto.HashFromBytes(responseBody),
  150. MimeType: responseHandler.ContentType(),
  151. Content: responseBody,
  152. }
  153. icon = resizeIcon(icon)
  154. return icon, nil
  155. }
  156. func resizeIcon(icon *model.Icon) *model.Icon {
  157. const (
  158. maxFaviconDimension = 4096
  159. maxFaviconPixels = 4096 * 4096
  160. )
  161. if icon.MimeType == "image/svg+xml" {
  162. minifier := minify.New()
  163. minifier.AddFunc("image/svg+xml", svg.Minify)
  164. var err error
  165. // minifier.Bytes returns the data unchanged in case of error.
  166. icon.Content, err = minifier.Bytes("image/svg+xml", icon.Content)
  167. if err != nil {
  168. slog.Error("Unable to minify SVG icon", slog.Any("error", err))
  169. }
  170. return icon
  171. }
  172. if !slices.Contains([]string{"image/jpeg", "image/png", "image/gif", "image/webp"}, icon.MimeType) {
  173. slog.Debug("Icon resize skipped: unsupported MIME type", slog.String("mime_type", icon.MimeType))
  174. return icon
  175. }
  176. r := bytes.NewReader(icon.Content)
  177. // Don't resize icons that we can't decode, or that already have the right size.
  178. config, _, err := image.DecodeConfig(r)
  179. if err != nil {
  180. slog.Warn("Unable to decode icon metadata", slog.Any("error", err))
  181. return icon
  182. }
  183. if config.Width <= 0 || config.Height <= 0 {
  184. slog.Warn("Icon resize skipped: invalid image dimensions",
  185. slog.Int("width", config.Width),
  186. slog.Int("height", config.Height),
  187. )
  188. return icon
  189. }
  190. pixelCount := int64(config.Width) * int64(config.Height)
  191. if config.Width > maxFaviconDimension || config.Height > maxFaviconDimension || pixelCount > maxFaviconPixels {
  192. slog.Warn("Icon rejected: image dimensions are too large",
  193. slog.Int("width", config.Width),
  194. slog.Int("height", config.Height),
  195. slog.Int64("pixel_count", pixelCount),
  196. )
  197. return nil
  198. }
  199. if config.Height <= 32 && config.Width <= 32 {
  200. slog.Debug("Icon doesn't need to be resized", slog.Int("height", config.Height), slog.Int("width", config.Width))
  201. return icon
  202. }
  203. r.Seek(0, io.SeekStart)
  204. var src image.Image
  205. switch icon.MimeType {
  206. case "image/jpeg":
  207. src, err = jpeg.Decode(r)
  208. case "image/png":
  209. src, err = png.Decode(r)
  210. case "image/gif":
  211. src, err = gif.Decode(r)
  212. case "image/webp":
  213. src, err = webp.Decode(r)
  214. }
  215. if err != nil || src == nil {
  216. slog.Warn("Unable to decode icon image", slog.Any("error", err))
  217. return icon
  218. }
  219. dst := image.NewRGBA(image.Rect(0, 0, 32, 32))
  220. draw.BiLinear.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)
  221. var b bytes.Buffer
  222. if err = png.Encode(io.Writer(&b), dst); err != nil {
  223. slog.Warn("Unable to encode resized icon", slog.Any("error", err))
  224. return icon
  225. }
  226. icon.Content = b.Bytes()
  227. icon.MimeType = "image/png"
  228. return icon
  229. }
  230. func findIconURLsFromHTMLDocument(documentURL string, body io.Reader, contentType string) ([]string, error) {
  231. htmlDocumentReader, err := encoding.NewCharsetReader(body, contentType)
  232. if err != nil {
  233. return nil, fmt.Errorf("icon: unable to create charset reader: %w", err)
  234. }
  235. doc, err := goquery.NewDocumentFromReader(htmlDocumentReader)
  236. if err != nil {
  237. return nil, fmt.Errorf("icon: unable to read document: %v", err)
  238. }
  239. query := `link[rel='icon' i][href],
  240. link[rel='shortcut icon' i][href],
  241. link[rel='icon shortcut' i][href],
  242. link[rel='apple-touch-icon'][href]`
  243. var iconURLs []string
  244. slog.Debug("Searching icon URL in HTML document", slog.String("query", query))
  245. for _, s := range doc.Find(query).EachIter() {
  246. href, _ := s.Attr("href")
  247. href = strings.TrimSpace(href)
  248. if href == "" {
  249. continue
  250. }
  251. if absoluteIconURL, err := urllib.ResolveToAbsoluteURL(documentURL, href); err != nil {
  252. slog.Warn("Unable to convert icon URL to absolute URL", slog.Any("error", err), slog.String("icon_href", href))
  253. } else {
  254. iconURLs = append(iconURLs, absoluteIconURL)
  255. slog.Debug("Found icon URL in HTML document",
  256. slog.String("query", query),
  257. slog.String("icon_href", href),
  258. slog.String("absolute_icon_url", absoluteIconURL),
  259. )
  260. }
  261. }
  262. return iconURLs, nil
  263. }
  264. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs#syntax
  265. // data:[<mediatype>][;encoding],<data>
  266. // we consider <mediatype> to be mandatory, and it has to start with `image/`.
  267. // we consider `base64`, `utf8` and the empty string to be the only valid encodings
  268. func parseImageDataURL(value string) (*model.Icon, error) {
  269. re := regexp.MustCompile(`^data:` +
  270. `(?P<mediatype>image/[^;,]+)` +
  271. `(?:;(?P<encoding>base64|utf8))?` +
  272. `,(?P<data>.+)$`)
  273. matches := re.FindStringSubmatch(value)
  274. if matches == nil {
  275. return nil, fmt.Errorf(`icon: invalid data URL %q`, value)
  276. }
  277. mediaType := matches[re.SubexpIndex("mediatype")]
  278. encoding := matches[re.SubexpIndex("encoding")]
  279. data := matches[re.SubexpIndex("data")]
  280. var blob []byte
  281. switch encoding {
  282. case "base64":
  283. var err error
  284. blob, err = base64.StdEncoding.DecodeString(data)
  285. if err != nil {
  286. return nil, fmt.Errorf(`icon: invalid data %q (%v)`, value, err)
  287. }
  288. case "":
  289. decodedData, err := url.QueryUnescape(data)
  290. if err != nil {
  291. return nil, fmt.Errorf(`icon: unable to decode data URL %q`, value)
  292. }
  293. blob = []byte(decodedData)
  294. case "utf8":
  295. blob = []byte(data)
  296. }
  297. return &model.Icon{
  298. Hash: crypto.HashFromBytes(blob),
  299. Content: blob,
  300. MimeType: mediaType,
  301. }, nil
  302. }