finder.go 9.3 KB

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