content_rewrite_functions.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package rewrite // import "miniflux.app/v2/internal/reader/rewrite"
  4. import (
  5. "encoding/base64"
  6. "fmt"
  7. "html"
  8. "log/slog"
  9. "net/url"
  10. "regexp"
  11. "slices"
  12. "strconv"
  13. "strings"
  14. "unicode"
  15. "miniflux.app/v2/internal/config"
  16. "miniflux.app/v2/internal/model"
  17. nethtml "golang.org/x/net/html"
  18. "golang.org/x/net/html/atom"
  19. "github.com/PuerkitoBio/goquery"
  20. )
  21. var (
  22. youtubeIdRegex = regexp.MustCompile(`youtube_id"?\s*[:=]\s*"([a-zA-Z0-9_-]{11})"`)
  23. textLinkRegex = regexp.MustCompile(`(?mi)(\bhttps?:\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])`)
  24. )
  25. // Rewrite rules insert content as nodes rather than HTML strings: goquery
  26. // panics when an HTML string fails to parse, and feed content controls it.
  27. // newlineNormalizer converts CRLF and CR line endings to LF, as the HTML parser does when it reads markup.
  28. var newlineNormalizer = strings.NewReplacer("\r\n", "\n", "\r", "\n")
  29. // newElementNode returns a detached element node with the given attributes and children.
  30. func newElementNode(tagName string, attributes []nethtml.Attribute, children ...*nethtml.Node) *nethtml.Node {
  31. for index := range attributes {
  32. attributes[index].Val = newlineNormalizer.Replace(attributes[index].Val)
  33. }
  34. element := &nethtml.Node{
  35. Type: nethtml.ElementNode,
  36. Data: tagName,
  37. DataAtom: atom.Lookup([]byte(tagName)),
  38. Attr: attributes,
  39. }
  40. for _, child := range children {
  41. element.AppendChild(child)
  42. }
  43. return element
  44. }
  45. // newTextNode returns a detached text node, escaped when the document is rendered.
  46. func newTextNode(text string) *nethtml.Node {
  47. return &nethtml.Node{Type: nethtml.TextNode, Data: newlineNormalizer.Replace(text)}
  48. }
  49. // rawTextElements are the elements whose text the renderer writes without escaping.
  50. var rawTextElements = []string{"iframe", "noembed", "noframes", "noscript", "plaintext", "script", "style", "xmp"}
  51. // titlelize returns a copy of the string s with all Unicode letters that begin words
  52. // mapped to their Unicode title case.
  53. func titlelize(s string) string {
  54. // A closure is used here to remember the previous character
  55. // so that we can check if there is a space preceding the current
  56. // character.
  57. previous := ' '
  58. return strings.Map(
  59. func(current rune) rune {
  60. if unicode.IsSpace(previous) {
  61. previous = current
  62. return unicode.ToTitle(current)
  63. }
  64. previous = current
  65. return current
  66. }, strings.ToLower(s))
  67. }
  68. func addImageTitle(entryContent string) string {
  69. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  70. if err != nil {
  71. return entryContent
  72. }
  73. matches := doc.Find("img[src][title]")
  74. if matches.Length() > 0 {
  75. matches.Each(func(i int, img *goquery.Selection) {
  76. altAttr := img.AttrOr("alt", "")
  77. srcAttr, _ := img.Attr("src")
  78. titleAttr, _ := img.Attr("title")
  79. img.ReplaceWithNodes(newElementNode("figure", nil,
  80. newElementNode("img", []nethtml.Attribute{{Key: "src", Val: srcAttr}, {Key: "alt", Val: altAttr}}),
  81. newElementNode("figcaption", nil,
  82. newElementNode("p", nil, newTextNode(titleAttr)),
  83. ),
  84. ))
  85. })
  86. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  87. return output
  88. }
  89. return entryContent
  90. }
  91. func addMailtoSubject(entryContent string) string {
  92. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  93. if err != nil {
  94. return entryContent
  95. }
  96. matches := doc.Find(`a[href^="mailto:"]`)
  97. if matches.Length() > 0 {
  98. matches.Each(func(i int, a *goquery.Selection) {
  99. hrefAttr, _ := a.Attr("href")
  100. mailto, err := url.Parse(hrefAttr)
  101. if err != nil {
  102. return
  103. }
  104. subject := mailto.Query().Get("subject")
  105. if subject == "" {
  106. return
  107. }
  108. a.AppendNodes(newTextNode(" [" + subject + "]"))
  109. })
  110. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  111. return output
  112. }
  113. return entryContent
  114. }
  115. func addDynamicImage(entryContent string) string {
  116. parserHtml, err := nethtml.ParseWithOptions(strings.NewReader(entryContent), nethtml.ParseOptionEnableScripting(false))
  117. if err != nil {
  118. return entryContent
  119. }
  120. doc := goquery.NewDocumentFromNode(parserHtml)
  121. // Ordered most preferred to least preferred.
  122. candidateAttrs := [...]string{
  123. "data-src",
  124. "data-original",
  125. "data-orig",
  126. "data-url",
  127. "data-orig-file",
  128. "data-large-file",
  129. "data-medium-file",
  130. "data-original-mos",
  131. "data-2000src",
  132. "data-1000src",
  133. "data-800src",
  134. "data-655src",
  135. "data-500src",
  136. "data-380src",
  137. }
  138. candidateSrcsetAttrs := [...]string{
  139. "data-srcset",
  140. }
  141. changed := false
  142. doc.Find("img,div").Each(func(i int, img *goquery.Selection) {
  143. // Src-linked candidates
  144. for _, candidateAttr := range candidateAttrs {
  145. if srcAttr, found := img.Attr(candidateAttr); found {
  146. changed = true
  147. if img.Is("img") {
  148. img.SetAttr("src", srcAttr)
  149. } else {
  150. altAttr := img.AttrOr("alt", "")
  151. img.ReplaceWithNodes(newElementNode("img", []nethtml.Attribute{{Key: "src", Val: srcAttr}, {Key: "alt", Val: altAttr}}))
  152. }
  153. break
  154. }
  155. }
  156. // Srcset-linked candidates
  157. for _, candidateAttr := range candidateSrcsetAttrs {
  158. if srcAttr, found := img.Attr(candidateAttr); found {
  159. changed = true
  160. if img.Is("img") {
  161. img.SetAttr("srcset", srcAttr)
  162. } else {
  163. altAttr := img.AttrOr("alt", "")
  164. img.ReplaceWithNodes(newElementNode("img", []nethtml.Attribute{{Key: "srcset", Val: srcAttr}, {Key: "alt", Val: altAttr}}))
  165. }
  166. break
  167. }
  168. }
  169. })
  170. if !changed {
  171. doc.Find("noscript").Each(func(i int, noscript *goquery.Selection) {
  172. if img := noscript.Find("img"); img.Length() == 1 {
  173. img.Unwrap()
  174. changed = true
  175. }
  176. })
  177. }
  178. if changed {
  179. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  180. return output
  181. }
  182. return entryContent
  183. }
  184. func addDynamicIframe(entryContent string) string {
  185. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  186. if err != nil {
  187. return entryContent
  188. }
  189. // Ordered most preferred to least preferred.
  190. candidateAttrs := []string{
  191. "data-src",
  192. "data-original",
  193. "data-orig",
  194. "data-url",
  195. "data-lazy-src",
  196. }
  197. changed := false
  198. doc.Find("iframe").Each(func(i int, iframe *goquery.Selection) {
  199. for _, candidateAttr := range candidateAttrs {
  200. if srcAttr, found := iframe.Attr(candidateAttr); found {
  201. changed = true
  202. iframe.SetAttr("src", srcAttr)
  203. break
  204. }
  205. }
  206. })
  207. if changed {
  208. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  209. return output
  210. }
  211. return entryContent
  212. }
  213. // The noscript rules parse the raw text of the noscript elements they replace
  214. // with nethtml.ParseFragment, which returns the error that goquery panics on.
  215. func fixMediumImages(entryContent string) string {
  216. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  217. if err != nil {
  218. return entryContent
  219. }
  220. doc.Find("figure.paragraph-image").Each(func(i int, paragraphImage *goquery.Selection) {
  221. noscriptElement := paragraphImage.Find("noscript")
  222. if noscriptElement.Length() > 0 {
  223. imageNodes, parseErr := nethtml.ParseFragment(strings.NewReader(noscriptElement.Text()), paragraphImage.Get(0).Parent)
  224. if parseErr != nil {
  225. return
  226. }
  227. paragraphImage.ReplaceWithNodes(imageNodes...)
  228. }
  229. })
  230. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  231. return output
  232. }
  233. func useNoScriptImages(entryContent string) string {
  234. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  235. if err != nil {
  236. return entryContent
  237. }
  238. doc.Find("figure").Each(func(i int, figureElement *goquery.Selection) {
  239. imgElement := figureElement.Find("img")
  240. if imgElement.Length() > 0 {
  241. noscriptElement := figureElement.Find("noscript")
  242. if noscriptElement.Length() > 0 {
  243. imageNodes, parseErr := nethtml.ParseFragment(strings.NewReader(noscriptElement.Text()), figureElement.Get(0))
  244. if parseErr != nil {
  245. return
  246. }
  247. figureElement.PrependNodes(imageNodes...)
  248. imgElement.Remove()
  249. noscriptElement.Remove()
  250. }
  251. }
  252. })
  253. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  254. return output
  255. }
  256. func getYoutubVideoIDFromURL(entryURL string) string {
  257. u, err := url.Parse(entryURL)
  258. if err != nil {
  259. return ""
  260. }
  261. hostname := u.Hostname()
  262. if hostname != "youtube.com" && !strings.HasSuffix(hostname, ".youtube.com") {
  263. return ""
  264. }
  265. if u.Path == "/watch" {
  266. if v := u.Query().Get("v"); v != "" {
  267. return v
  268. }
  269. return ""
  270. }
  271. if id, found := strings.CutPrefix(u.Path, "/shorts/"); found {
  272. if len(id) == 11 {
  273. // youtube shorts id are always 11 chars.
  274. return id
  275. }
  276. }
  277. return ""
  278. }
  279. func buildVideoPlayerIframe(absoluteVideoURL string) string {
  280. return `<iframe width="650" height="350" frameborder="0" src="` + absoluteVideoURL + `" allowfullscreen></iframe>`
  281. }
  282. func addVideoPlayerIframe(absoluteVideoURL, entryContent string) string {
  283. return buildVideoPlayerIframe(absoluteVideoURL) + `<br>` + entryContent
  284. }
  285. func addYoutubeVideoRewriteRule(entryURL, entryContent string) string {
  286. if videoURL := getYoutubVideoIDFromURL(entryURL); videoURL != "" {
  287. return addVideoPlayerIframe(config.Opts.YouTubeEmbedUrlOverride()+videoURL, entryContent)
  288. }
  289. return entryContent
  290. }
  291. func addYoutubeVideoUsingInvidiousPlayer(entryURL, entryContent string) string {
  292. if videoURL := getYoutubVideoIDFromURL(entryURL); videoURL != "" {
  293. return addVideoPlayerIframe(`https://`+config.Opts.InvidiousInstance()+`/embed/`+videoURL, entryContent)
  294. }
  295. return entryContent
  296. }
  297. // For reference: https://github.com/miniflux/v2/pull/1314
  298. func addYoutubeVideoFromId(entryContent string) string {
  299. matches := youtubeIdRegex.FindAllStringSubmatch(entryContent, -1)
  300. if matches == nil {
  301. return entryContent
  302. }
  303. var videoPlayerHTML strings.Builder
  304. for _, match := range matches {
  305. if len(match) == 2 {
  306. videoPlayerHTML.WriteString(buildVideoPlayerIframe(config.Opts.YouTubeEmbedUrlOverride() + match[1]))
  307. videoPlayerHTML.WriteString("<br>")
  308. }
  309. }
  310. return videoPlayerHTML.String() + entryContent
  311. }
  312. func addInvidiousVideo(entryURL, entryContent string) string {
  313. u, err := url.Parse(entryURL)
  314. if err != nil {
  315. return entryContent
  316. }
  317. if u.Path != "/watch" {
  318. return entryContent
  319. }
  320. qs := u.Query()
  321. videoID := qs.Get("v")
  322. if videoID == "" {
  323. return entryContent
  324. }
  325. qs.Del("v")
  326. embedVideoURL := "https://" + u.Hostname() + `/embed/` + videoID
  327. if len(qs) > 0 {
  328. embedVideoURL += "?" + qs.Encode()
  329. }
  330. return addVideoPlayerIframe(embedVideoURL, entryContent)
  331. }
  332. func addPDFLink(entryURL, entryContent string) string {
  333. if strings.HasSuffix(entryURL, ".pdf") {
  334. return fmt.Sprintf(`<a href=%q>PDF</a><br>%s`, entryURL, entryContent)
  335. }
  336. return entryContent
  337. }
  338. func addEnclosureLinks(entry *model.Entry) string {
  339. var links strings.Builder
  340. for _, enclosure := range entry.Enclosures {
  341. if enclosure.URL == "" {
  342. continue
  343. }
  344. enclosureURL := html.EscapeString(enclosure.URL)
  345. links.WriteString(`<li><a href="` + enclosureURL + `">` + enclosureURL + `</a></li>`)
  346. }
  347. if links.Len() > 0 {
  348. return entry.Content + "<hr/><ul>" + strings.TrimSpace(links.String()) + "</ul>"
  349. }
  350. return entry.Content
  351. }
  352. func replaceTextLinks(input string) string {
  353. return textLinkRegex.ReplaceAllString(input, `<a href="${1}">${1}</a>`)
  354. }
  355. func replaceCustom(entryContent string, searchTerm string, replaceTerm string) string {
  356. re, err := regexp.Compile(searchTerm)
  357. if err == nil {
  358. return re.ReplaceAllString(entryContent, replaceTerm)
  359. }
  360. return entryContent
  361. }
  362. func removeCustom(entryContent string, selector string) string {
  363. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  364. if err != nil {
  365. return entryContent
  366. }
  367. doc.Find(selector).Remove()
  368. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  369. return output
  370. }
  371. func addCastopodEpisode(entryURL, entryContent string) string {
  372. player := `<iframe width="650" frameborder="0" src="` + entryURL + `/embed/light"></iframe>`
  373. return player + `<br>` + entryContent
  374. }
  375. // applyFuncOnTextContent replaces the text nodes under the selector with the plain text returned by repl.
  376. func applyFuncOnTextContent(entryContent string, selector string, repl func(string) string) string {
  377. var treatChildren func(i int, s *goquery.Selection)
  378. treatChildren = func(i int, s *goquery.Selection) {
  379. node := s.Nodes[0]
  380. switch {
  381. case node.Type == nethtml.TextNode:
  382. node.Data = newlineNormalizer.Replace(repl(node.Data))
  383. case node.Type == nethtml.ElementNode && slices.Contains(rawTextElements, node.Data):
  384. // Skipped: replacement text rendered without escaping could close the element.
  385. default:
  386. s.Contents().Each(treatChildren)
  387. }
  388. }
  389. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  390. if err != nil {
  391. return entryContent
  392. }
  393. doc.Find(selector).Each(treatChildren)
  394. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  395. return output
  396. }
  397. func decodeBase64Content(entryContent string) string {
  398. if ret, err := base64.StdEncoding.DecodeString(strings.TrimSpace(entryContent)); err != nil {
  399. return entryContent
  400. } else {
  401. return string(ret)
  402. }
  403. }
  404. func addHackerNewsLinksUsing(entryContent, app string) string {
  405. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  406. if err != nil {
  407. return entryContent
  408. }
  409. hn_prefix := "https://news.ycombinator.com/"
  410. matches := doc.Find(`a[href^="` + hn_prefix + `"]`)
  411. if matches.Length() > 0 {
  412. matches.Each(func(i int, a *goquery.Selection) {
  413. hrefAttr, _ := a.Attr("href")
  414. hn_uri, err := url.Parse(hrefAttr)
  415. if err != nil {
  416. return
  417. }
  418. switch app {
  419. case "opener":
  420. params := url.Values{}
  421. params.Add("url", hn_uri.String())
  422. url := url.URL{
  423. Scheme: "opener",
  424. Host: "x-callback-url",
  425. Path: "show-options",
  426. RawQuery: params.Encode(),
  427. }
  428. openerLink := newElementNode("a", []nethtml.Attribute{{Key: "href", Val: url.String()}}, newTextNode("Open with Opener"))
  429. a.Parent().AppendNodes(newTextNode(" "), openerLink)
  430. case "hack":
  431. url := strings.Replace(hn_uri.String(), hn_prefix, "hack://", 1)
  432. hackLink := newElementNode("a", []nethtml.Attribute{{Key: "href", Val: url}}, newTextNode("Open with HACK"))
  433. a.Parent().AppendNodes(newTextNode(" "), hackLink)
  434. default:
  435. slog.Warn("Unknown app provided for openHackerNewsLinksWith rewrite rule",
  436. slog.String("app", app),
  437. )
  438. return
  439. }
  440. })
  441. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  442. return output
  443. }
  444. return entryContent
  445. }
  446. func removeTables(entryContent string) string {
  447. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  448. if err != nil {
  449. return entryContent
  450. }
  451. // Column definitions have no content to keep.
  452. doc.Find("col").Remove()
  453. // Replace each table element with its own content in place, so the
  454. // surrounding content keeps its original document order.
  455. // Appending to the parent would move the unwrapped content to
  456. // the end of the parent instead.
  457. doc.Find("table, caption, colgroup, thead, tbody, tfoot, tr, th, td").Each(func(_ int, tableElement *goquery.Selection) {
  458. tableElement.ReplaceWithSelection(tableElement.Contents())
  459. })
  460. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  461. return output
  462. }
  463. func fixGhostCards(entryContent string) string {
  464. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  465. if err != nil {
  466. return entryContent
  467. }
  468. const cardSelector = "figure.kg-card"
  469. var currentList *nethtml.Node
  470. doc.Find(cardSelector).Each(func(i int, s *goquery.Selection) {
  471. title := s.Find(".kg-bookmark-title").First().Text()
  472. author := s.Find(".kg-bookmark-author").First().Text()
  473. href := s.Find("a.kg-bookmark-container").First().AttrOr("href", "")
  474. // if there is no link or title, skip processing
  475. if href == "" || title == "" {
  476. return
  477. }
  478. linkText := title
  479. if author != "" && !strings.HasSuffix(title, author) {
  480. linkText = title + " - " + author
  481. }
  482. link := newElementNode("a", []nethtml.Attribute{{Key: "href", Val: href}}, newTextNode(linkText))
  483. next := s.Next()
  484. // if the next element is also a card, start a list
  485. if next.Is(cardSelector) && currentList == nil {
  486. currentList = newElementNode("ul", nil)
  487. s.BeforeNodes(currentList)
  488. }
  489. if currentList != nil {
  490. // add this card to the list, then delete it
  491. currentList.AppendChild(newElementNode("li", nil, link))
  492. s.Remove()
  493. } else {
  494. // replace single card
  495. s.ReplaceWithNodes(link)
  496. }
  497. // if the next element is not a card, start a new list
  498. if !next.Is(cardSelector) && currentList != nil {
  499. currentList = nil
  500. }
  501. })
  502. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  503. return strings.TrimSpace(output)
  504. }
  505. func removeImgBlurParams(entryContent string) string {
  506. doc, err := goquery.NewDocumentFromReader(strings.NewReader(entryContent))
  507. if err != nil {
  508. return entryContent
  509. }
  510. changed := false
  511. doc.Find("img[src]").Each(func(i int, img *goquery.Selection) {
  512. srcAttr, exists := img.Attr("src")
  513. if !exists {
  514. return
  515. }
  516. parsedURL, err := url.Parse(srcAttr)
  517. if err != nil {
  518. return
  519. }
  520. // Only strip query parameters if this is a blurry placeholder image
  521. if parsedURL.RawQuery != "" {
  522. // Check if there's a blur parameter with a non-zero value
  523. if blurValue := parsedURL.Query().Get("blur"); blurValue != "" {
  524. if blurInt, err := strconv.Atoi(blurValue); err == nil && blurInt > 0 {
  525. parsedURL.RawQuery = ""
  526. img.SetAttr("src", parsedURL.String())
  527. changed = true
  528. }
  529. }
  530. }
  531. })
  532. if changed {
  533. output, _ := doc.FindMatcher(goquery.Single("body")).Html()
  534. return output
  535. }
  536. return entryContent
  537. }