4
0

finder.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. "golang.org/x/image/draw"
  26. )
  27. type IconFinder struct {
  28. requestBuilder *fetcher.RequestBuilder
  29. websiteURL string
  30. feedIconURL string
  31. }
  32. func NewIconFinder(requestBuilder *fetcher.RequestBuilder, websiteURL, feedIconURL string) *IconFinder {
  33. return &IconFinder{
  34. requestBuilder: requestBuilder,
  35. websiteURL: websiteURL,
  36. feedIconURL: feedIconURL,
  37. }
  38. }
  39. func (f *IconFinder) FindIcon() (*model.Icon, error) {
  40. slog.Debug("Begin icon discovery process",
  41. slog.String("website_url", f.websiteURL),
  42. slog.String("feed_icon_url", f.feedIconURL),
  43. )
  44. if f.feedIconURL != "" {
  45. if icon, err := f.FetchFeedIcon(); err != nil {
  46. slog.Debug("Unable to download icon from feed",
  47. slog.String("website_url", f.websiteURL),
  48. slog.String("feed_icon_url", f.feedIconURL),
  49. slog.Any("error", err),
  50. )
  51. } else if icon != nil {
  52. return icon, nil
  53. }
  54. }
  55. if icon, err := f.FetchIconsFromHTMLDocument(); err != nil {
  56. slog.Debug("Unable to fetch icons from HTML document",
  57. slog.String("website_url", f.websiteURL),
  58. slog.Any("error", err),
  59. )
  60. } else if icon != nil {
  61. return icon, nil
  62. }
  63. return f.FetchDefaultIcon()
  64. }
  65. func (f *IconFinder) FetchDefaultIcon() (*model.Icon, error) {
  66. slog.Debug("Fetching default icon",
  67. slog.String("website_url", f.websiteURL),
  68. )
  69. iconURL, err := urllib.JoinBaseURLAndPath(urllib.RootURL(f.websiteURL), "favicon.ico")
  70. if err != nil {
  71. return nil, fmt.Errorf(`icon: unable to join root URL and path: %w`, err)
  72. }
  73. icon, err := f.DownloadIcon(iconURL)
  74. if err != nil {
  75. return nil, err
  76. }
  77. return icon, nil
  78. }
  79. func (f *IconFinder) FetchFeedIcon() (*model.Icon, error) {
  80. slog.Debug("Fetching feed icon",
  81. slog.String("website_url", f.websiteURL),
  82. slog.String("feed_icon_url", f.feedIconURL),
  83. )
  84. iconURL, err := urllib.AbsoluteURL(f.websiteURL, f.feedIconURL)
  85. if err != nil {
  86. return nil, fmt.Errorf(`icon: unable to convert icon URL to absolute URL: %w`, err)
  87. }
  88. return f.DownloadIcon(iconURL)
  89. }
  90. func (f *IconFinder) FetchIconsFromHTMLDocument() (*model.Icon, error) {
  91. slog.Debug("Searching icons from HTML document",
  92. slog.String("website_url", f.websiteURL),
  93. )
  94. rootURL := urllib.RootURL(f.websiteURL)
  95. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(rootURL))
  96. defer responseHandler.Close()
  97. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  98. return nil, fmt.Errorf("icon: unable to download website index page: %w", localizedError.Error())
  99. }
  100. iconURLs, err := findIconURLsFromHTMLDocument(
  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("website_url", f.websiteURL),
  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("website_url", f.websiteURL),
  115. )
  116. return parseImageDataURL(iconURL)
  117. }
  118. iconURL, err = urllib.AbsoluteURL(f.websiteURL, iconURL)
  119. if err != nil {
  120. return nil, fmt.Errorf(`icon: unable to convert icon URL to absolute URL: %w`, err)
  121. }
  122. if icon, err := f.DownloadIcon(iconURL); err != nil {
  123. slog.Debug("Unable to download icon from HTML document",
  124. slog.String("website_url", f.websiteURL),
  125. slog.String("icon_url", iconURL),
  126. slog.Any("error", err),
  127. )
  128. } else if icon != nil {
  129. slog.Debug("Found icon from HTML document",
  130. slog.String("website_url", f.websiteURL),
  131. slog.String("icon_url", iconURL),
  132. )
  133. return icon, nil
  134. }
  135. }
  136. return nil, nil
  137. }
  138. func (f *IconFinder) DownloadIcon(iconURL string) (*model.Icon, error) {
  139. slog.Debug("Downloading icon",
  140. slog.String("website_url", f.websiteURL),
  141. slog.String("icon_url", iconURL),
  142. )
  143. responseHandler := fetcher.NewResponseHandler(f.requestBuilder.ExecuteRequest(iconURL))
  144. defer responseHandler.Close()
  145. if localizedError := responseHandler.LocalizedError(); localizedError != nil {
  146. return nil, fmt.Errorf("icon: unable to download website icon: %w", localizedError.Error())
  147. }
  148. responseBody, localizedError := responseHandler.ReadBody(config.Opts.HTTPClientMaxBodySize())
  149. if localizedError != nil {
  150. return nil, fmt.Errorf("icon: unable to read response body: %w", localizedError.Error())
  151. }
  152. icon := &model.Icon{
  153. Hash: crypto.HashFromBytes(responseBody),
  154. MimeType: responseHandler.ContentType(),
  155. Content: responseBody,
  156. }
  157. icon = resizeIcon(icon)
  158. return icon, nil
  159. }
  160. func resizeIcon(icon *model.Icon) *model.Icon {
  161. r := bytes.NewReader(icon.Content)
  162. if !slices.Contains([]string{"image/jpeg", "image/png", "image/gif"}, icon.MimeType) {
  163. slog.Info("icon isn't a png/gif/jpeg/ico, can't resize", slog.String("mimetype", icon.MimeType))
  164. return icon
  165. }
  166. // Don't resize icons that we can't decode, or that already have the right size.
  167. config, _, err := image.DecodeConfig(r)
  168. if err != nil {
  169. slog.Warn("unable to decode the metadata of the icon", slog.Any("error", err))
  170. return icon
  171. }
  172. if config.Height <= 32 && config.Width <= 32 {
  173. slog.Debug("icon don't need to be rescaled", slog.Int("height", config.Height), slog.Int("width", config.Width))
  174. return icon
  175. }
  176. r.Seek(0, io.SeekStart)
  177. var src image.Image
  178. switch icon.MimeType {
  179. case "image/jpeg":
  180. src, err = jpeg.Decode(r)
  181. case "image/png":
  182. src, err = png.Decode(r)
  183. case "image/gif":
  184. src, err = gif.Decode(r)
  185. }
  186. if err != nil || src == nil {
  187. slog.Warn("unable to decode the icon", slog.Any("error", err))
  188. return icon
  189. }
  190. dst := image.NewRGBA(image.Rect(0, 0, 32, 32))
  191. draw.BiLinear.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)
  192. var b bytes.Buffer
  193. if err = png.Encode(io.Writer(&b), dst); err != nil {
  194. slog.Warn("unable to encode the new icon", slog.Any("error", err))
  195. }
  196. icon.Content = b.Bytes()
  197. icon.MimeType = "image/png"
  198. return icon
  199. }
  200. func findIconURLsFromHTMLDocument(body io.Reader, contentType string) ([]string, error) {
  201. queries := []string{
  202. "link[rel='icon' i]",
  203. "link[rel='shortcut icon' i]",
  204. "link[rel='icon shortcut' i]",
  205. "link[rel='apple-touch-icon-precomposed.png']",
  206. }
  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. var iconURLs []string
  216. for _, query := range queries {
  217. slog.Debug("Searching icon URL in HTML document", slog.String("query", query))
  218. doc.Find(query).Each(func(i int, s *goquery.Selection) {
  219. if href, exists := s.Attr("href"); exists {
  220. if iconURL := strings.TrimSpace(href); iconURL != "" {
  221. iconURLs = append(iconURLs, iconURL)
  222. slog.Debug("Found icon URL in HTML document",
  223. slog.String("query", query),
  224. slog.String("icon_url", iconURL))
  225. }
  226. }
  227. })
  228. }
  229. return iconURLs, nil
  230. }
  231. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs#syntax
  232. // data:[<mediatype>][;encoding],<data>
  233. // we consider <mediatype> to be mandatory, and it has to start with `image/`.
  234. // we consider `base64`, `utf8` and the empty string to be the only valid encodings
  235. func parseImageDataURL(value string) (*model.Icon, error) {
  236. re := regexp.MustCompile(`^data:` +
  237. `(?P<mediatype>image/[^;,]+)` +
  238. `(?:;(?P<encoding>base64|utf8))?` +
  239. `,(?P<data>.+)$`)
  240. matches := re.FindStringSubmatch(value)
  241. if matches == nil {
  242. return nil, fmt.Errorf(`icon: invalid data URL %q`, value)
  243. }
  244. mediaType := matches[re.SubexpIndex("mediatype")]
  245. encoding := matches[re.SubexpIndex("encoding")]
  246. data := matches[re.SubexpIndex("data")]
  247. var blob []byte
  248. switch encoding {
  249. case "base64":
  250. var err error
  251. blob, err = base64.StdEncoding.DecodeString(data)
  252. if err != nil {
  253. return nil, fmt.Errorf(`icon: invalid data %q (%v)`, value, err)
  254. }
  255. case "":
  256. decodedData, err := url.QueryUnescape(data)
  257. if err != nil {
  258. return nil, fmt.Errorf(`icon: unable to decode data URL %q`, value)
  259. }
  260. blob = []byte(decodedData)
  261. case "utf8":
  262. blob = []byte(data)
  263. }
  264. return &model.Icon{
  265. Hash: crypto.HashFromBytes(blob),
  266. Content: blob,
  267. MimeType: mediaType,
  268. }, nil
  269. }